#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 公共函数定义
# 格式化列表项显示
format_list_item() {
    local number="$1"
    local title="$2"
    local description="$3"
    local max_title_length=20
    
    # 计算标题长度，确保对齐
    local title_length=${#title}
    local padding=""
    if [ $title_length -lt $max_title_length ]; then
        local padding_length=$((max_title_length - title_length))
        padding=$(printf '%*s' $padding_length '')
    fi
    
    echo -e "${CYAN}$number.${NC} ${WHITE}$title${NC}$padding  ${description}"
}

# 显示分隔线
show_separator() {
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# 显示标题
show_title() {
    local title="$1"
    echo -e "${WHITE}$title${NC}"
}

# 显示状态图标
show_status_icon() {
    local status="$1"
    case "$status" in
        "running") echo -e "${GREEN}✅${NC}" ;;
        "stopped") echo -e "${RED}❌${NC}" ;;
        "warning") echo -e "${YELLOW}⚠️${NC}" ;;
        "info") echo -e "${CYAN}💡${NC}" ;;
        *) echo -e "${WHITE}•${NC}" ;;
    esac
}

# 验证端口号
validate_port() {
    local port="$1"
    if [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ]; then
        return 0
    else
        return 1
    fi
}

# 验证域名格式
validate_domain() {
    local domain="$1"
    if [[ "$domain" =~ ^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$ ]]; then
        return 0
    else
        return 1
    fi
}

# 获取Nginx状态信息
get_nginx_status() {
    local status_info=""
    
    # 服务状态
    if systemctl is-active --quiet nginx; then
        status_info+="运行中"
    else
        status_info+="已停止"
    fi
    
    # 开机自启状态
    if systemctl is-enabled --quiet nginx; then
        status_info+="|开机自启"
    else
        status_info+="|未自启"
    fi
    
    # 版本信息
    local nginx_version=$(nginx -v 2>&1 | grep -o 'nginx/[0-9.]*' | cut -d'/' -f2)
    status_info+="|版本:$nginx_version"
    
    echo "$status_info"
}

# 格式化显示Nginx状态
display_nginx_status() {
    local status_info=$(get_nginx_status)
    local service_status=$(echo "$status_info" | cut -d'|' -f1)
    local auto_start=$(echo "$status_info" | cut -d'|' -f2)
    local version=$(echo "$status_info" | cut -d'|' -f3 | cut -d':' -f2)
    
    echo -e "${WHITE}📊 服务状态：${NC}"
    if [ "$service_status" = "运行中" ]; then
        echo -e "  ${GREEN}✅ 运行中${NC}"
    else
        echo -e "  ${RED}❌ 已停止${NC}"
    fi
    
    if [ "$auto_start" = "开机自启" ]; then
        echo -e "  ${GREEN}✅ 开机自启${NC}"
    else
        echo -e "  ${YELLOW}⚠️  未设置开机自启${NC}"
    fi
    
    echo -e "  ${CYAN}📋 版本信息：${NC} ${WHITE}Nginx $version${NC}"
    
    # 端口监听状态
    echo -e "  ${CYAN}🌐 端口监听：${NC}"
    if netstat -tlnp 2>/dev/null | grep -q ":80.*nginx"; then
        echo -e "    ${GREEN}✅ 80端口 (HTTP)${NC}"
    else
        echo -e "    ${RED}❌ 80端口未监听${NC}"
    fi
    
    if netstat -tlnp 2>/dev/null | grep -q ":443.*nginx"; then
        echo -e "    ${GREEN}✅ 443端口 (HTTPS)${NC}"
    else
        echo -e "    ${YELLOW}⚠️  443端口未监听${NC}"
    fi
}

# 安装目录
INSTALL_DIR="/www/server"
WWW_DIR="/www/server"

# 初始化变量
Jdk=0
Tomcat=0
Maven=0
Nginx=0
MySQL=0
Redis=0
SVN=0
FTP=0
ZooKeeper=0
RabbitMQ=0
Kafka=0
ELK=0
Ngrok=0
Nodejs=0

# 显示欢迎界面
show_welcome() {
    clear
    echo -e "${CYAN}"
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}                    ${WHITE}Java开发环境一键安装脚本${NC}                  ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}支持组件：${NC} ${CYAN}Nginx, JDK, Tomcat, MySQL, Maven${NC}               ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}         ${NC} ${CYAN}Redis, SVN, FTP, ZooKeeper, RabbitMQ${NC}            ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}         ${NC} ${CYAN}Kafka, ELK Stack, Ngrok${NC}                         ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}适用系统：${NC} ${CYAN}CentOS 7+ / RHEL 7+${NC}                            ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}安装位置：${NC} ${CYAN}/www/server (所有组件)${NC}                         ${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🚀 开始选择安装组件${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
}

# 显示安装选择菜单
show_install_menu() {
    echo -e "${CYAN}"
    echo -e "${GREEN}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║${NC}                         ${WHITE}安装选择菜单${NC}                         ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                                                              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 1.${NC} ${CYAN}JDK 1.8${NC}                    ${WHITE} 7.${NC} ${CYAN}Redis${NC}                  ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 2.${NC} ${CYAN}Tomcat 9.x${NC}                 ${WHITE} 8.${NC} ${CYAN}SVN${NC}                    ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 3.${NC} ${CYAN}Maven${NC}                      ${WHITE} 9.${NC} ${CYAN}FTP${NC}                    ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 4.${NC} ${CYAN}Nginx${NC}                      ${WHITE}10.${NC} ${CYAN}ZooKeeper${NC}              ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 5.${NC} ${CYAN}MySQL 5.7${NC}                  ${WHITE}11.${NC} ${CYAN}RabbitMQ${NC}               ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE} 6.${NC} ${CYAN}ELK Stack${NC}                  ${WHITE}12.${NC} ${CYAN}Kafka${NC}                  ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}    ${WHITE}13.${NC} ${CYAN}Ngrok${NC}                      ${WHITE}14.${NC} ${CYAN}Node.js${NC}                ${GREEN}║${NC}"
    echo -e "${GREEN}║${NC}                        ${WHITE} 0.${NC} ${RED}重新选择${NC}                          ${GREEN}║${NC}"
    echo -e "${GREEN}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo -e "${YELLOW}💡 提示：Ctrl+C 关闭脚本${NC}"
    echo 
}

# 显示已选择组件列表
show_selected_components() {
    local selected_count=0
    local selected_items=()
    
    # 统计已选择的组件
    if [ $Jdk == "1" ]; then selected_items+=("1.JDK 1.8"); ((selected_count++)); fi
    if [ $Tomcat == "1" ]; then selected_items+=("2.Tomcat 9.x"); ((selected_count++)); fi
    if [ $Maven == "1" ]; then selected_items+=("3.Maven"); ((selected_count++)); fi
    if [ $Nginx == "1" ]; then selected_items+=("4.Nginx"); ((selected_count++)); fi
    if [ $MySQL == "1" ]; then selected_items+=("5.MySQL 5.7"); ((selected_count++)); fi
    if [ $Redis == "1" ]; then selected_items+=("7.Redis"); ((selected_count++)); fi
    if [ $SVN == "1" ]; then selected_items+=("8.SVN"); ((selected_count++)); fi
    if [ $FTP == "1" ]; then selected_items+=("9.FTP"); ((selected_count++)); fi
    if [ $ZooKeeper == "1" ]; then selected_items+=("10.ZooKeeper"); ((selected_count++)); fi
    if [ $RabbitMQ == "1" ]; then selected_items+=("11.RabbitMQ"); ((selected_count++)); fi
    if [ $Kafka == "1" ]; then selected_items+=("12.Kafka"); ((selected_count++)); fi
    if [ $ELK == "1" ]; then selected_items+=("6.ELK Stack"); ((selected_count++)); fi
    if [ $Ngrok == "1" ]; then selected_items+=("13.Ngrok"); ((selected_count++)); fi
    if [ $Nodejs == "1" ]; then selected_items+=("14.Node.js"); ((selected_count++)); fi
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📋 已选择组件列表 (共 ${GREEN}$selected_count${NC} 个)${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if [ $selected_count -gt 0 ]; then
        # 显示已选择的组件
        for item in "${selected_items[@]}"; do
            echo -e "  ${GREEN}✅ $item${NC}"
        done
    else
        echo -e "  ${RED}❌ 暂未选择任何组件${NC}"
    fi
    echo
}

# 检测组件是否已安装
check_component_installed() {
    local component_name="$1"
    local check_command="$2"
    local install_path="$3"
    
    if command -v "$check_command" &> /dev/null || [ -d "$install_path" ]; then
        return 0  # 已安装
    else
        return 1  # 未安装
    fi
}

# 卸载组件
uninstall_component() {
    local component_name="$1"
    local uninstall_commands="$2"
    
    echo -e "${YELLOW}正在卸载 $component_name...${NC}"
    eval "$uninstall_commands"
    echo -e "${GREEN}✅ $component_name 卸载完成！${NC}"
    
    # 询问是否要重新安装
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔄 重新安装选项${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    read -p "是否要重新安装 $component_name？(y/n，默认n): " reinstall_choice
    if [[ $reinstall_choice =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}继续安装 $component_name...${NC}"
        return 0
    else
        echo -e "${YELLOW}跳过 $component_name 重新安装${NC}"
        return 1
    fi
}

# 显示详细选择状态
show_selection_status() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📋 详细安装选择状态${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    components=(
        "JDK 1.8:$Jdk"
        "Tomcat 9.x:$Tomcat"
        "Maven:$Maven"
        "Nginx:$Nginx"
        "MySQL 5.7:$MySQL"
        "Redis:$Redis"
        "SVN:$SVN"
        "FTP:$FTP"
        "ZooKeeper:$ZooKeeper"
        "RabbitMQ:$RabbitMQ"
        "Kafka:$Kafka"
        "ELK Stack:$ELK"
        "Ngrok:$Ngrok"
    )
    
    local selected_count=0
    local total_count=0
    
    for component in "${components[@]}"; do
        name=$(echo "$component" | cut -d: -f1)
        status=$(echo "$component" | cut -d: -f2)
        ((total_count++))
        if [ "$status" == "1" ]; then
            echo -e "${GREEN}✅ $name${NC}"
            ((selected_count++))
        else
            echo -e "${RED}❌ $name${NC}"
        fi
    done
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📊 选择统计：${GREEN}$selected_count${NC}/${CYAN}$total_count${NC} 个组件${NC}"
    
    if [ $selected_count -gt 0 ]; then
        echo -e "${YELLOW}💡 下一步操作：${NC}"
        echo -e "  • 开始安装: 输入 ${CYAN}15${NC}"
        echo -e "  • 继续选择: 返回主菜单"
        echo -e "  • 退出安装: 输入 ${RED}0${NC}"
    else
        echo -e "${YELLOW}💡 请至少选择一个组件进行安装${NC}"
    fi
    echo
}

# 安装JDK 1.8
install_jdk() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装JDK 1.8${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "JDK" "java" "/usr/java/jdk1.8.0_131"; then
        echo -e "${YELLOW}⚠️  JDK 已安装${NC}"
        read -p "是否要卸载现有JDK？(y/n，默认n): " uninstall_jdk
        if [[ $uninstall_jdk =~ ^[Yy]$ ]]; then
            uninstall_component "JDK" "rpm -e jdk1.8.0_131"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
            # 清理环境变量
            sed -i '/JAVA_HOME/d' /etc/profile
            sed -i '/export PATH.*java/d' /etc/profile
            sed -i '/CLASSPATH/d' /etc/profile
        else
            echo -e "${YELLOW}跳过JDK安装${NC}"
            return
        fi
    fi
    
    mkdir -p $INSTALL_DIR
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}正在下载JDK 1.8...${NC}"
    wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm
    
    echo -e "${YELLOW}正在安装JDK...${NC}"
    chmod +x jdk-8u131-linux-x64.rpm
    rpm -ivh jdk-8u131-linux-x64.rpm
    
    echo -e "${YELLOW}配置JDK环境变量...${NC}"
    echo 'export JAVA_HOME=/usr/java/jdk1.8.0_131' >> /etc/profile
    echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile
    echo 'export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar' >> /etc/profile
    source /etc/profile
    
    echo -e "${YELLOW}验证JDK安装...${NC}"
    java -version
    javac -version
    
    echo -e "${GREEN}✅ JDK 1.8 安装完成！${NC}"
}

# 安装Tomcat 9.x
install_tomcat() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Tomcat 9.x${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Tomcat" "catalina" "/www/server/tomcat"; then
        echo -e "${YELLOW}⚠️  Tomcat 已安装${NC}"
        read -p "是否要卸载现有Tomcat？(y/n，默认n): " uninstall_tomcat
        if [[ $uninstall_tomcat =~ ^[Yy]$ ]]; then
            uninstall_component "Tomcat" "rm -rf /www/server/tomcat"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
            # 清理环境变量
            sed -i '/CATALINA_HOME/d' /etc/profile
        else
            echo -e "${YELLOW}跳过Tomcat安装${NC}"
            return
        fi
    fi
    
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}正在下载Tomcat 9.0.10...${NC}"
    wget https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.10/bin/apache-tomcat-9.0.10.tar.gz
    
    echo -e "${YELLOW}正在解压Tomcat...${NC}"
    tar -xzf apache-tomcat-9.0.10.tar.gz
    mv apache-tomcat-9.0.10 /www/server/tomcat
    
    echo -e "${YELLOW}配置Tomcat环境变量...${NC}"
    echo 'export CATALINA_HOME=/www/server/tomcat' >> /etc/profile
    echo 'export PATH=$CATALINA_HOME/bin:$PATH' >> /etc/profile
    
    echo -e "${YELLOW}设置Tomcat权限...${NC}"
    chmod +x /www/server/tomcat/bin/*.sh
    
    echo -e "${YELLOW}验证Tomcat安装...${NC}"
    /www/server/tomcat/bin/version.sh
    
    echo -e "${YELLOW}启动Tomcat服务...${NC}"
    /www/server/tomcat/bin/startup.sh
    
    echo -e "${YELLOW}配置Tomcat开机自启...${NC}"
    # 创建systemd服务文件
    cat > /etc/systemd/system/tomcat.service << EOF
[Unit]
Description=Apache Tomcat Web Application Container
After=network.target

[Service]
Type=forking
Environment=JAVA_HOME=/usr/java/jdk1.8.0_131
Environment=CATALINA_HOME=/www/server/tomcat
Environment=CATALINA_BASE=/www/server/tomcat
Environment=CATALINA_TMPDIR=/www/server/tomcat/temp
Environment=JRE_HOME=/usr/java/jdk1.8.0_131
Environment=CLASSPATH=/www/server/tomcat/bin/bootstrap.jar:/www/server/tomcat/bin/tomcat-juli.jar

ExecStart=/www/server/tomcat/bin/startup.sh
ExecStop=/www/server/tomcat/bin/shutdown.sh
ExecReload=/bin/kill -s HUP \$MAINPID

User=root
Group=root
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target
EOF

    # 重新加载systemd配置
    systemctl daemon-reload
    
    # 启用开机自启
    systemctl enable tomcat.service
    
    # 验证Tomcat是否启动成功
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔍 验证Tomcat安装${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    sleep 3
    if pgrep -f "tomcat" > /dev/null; then
        echo -e "${GREEN}✅ Tomcat 安装完成并启动成功！${NC}"
        echo -e "${CYAN}Tomcat进程信息：${NC}"
        ps -ef | grep tomcat | grep -v grep
        echo
        echo -e "${CYAN}访问信息：${NC}"
        echo -e "  验证地址: ${CYAN}http://$(curl -s ipinfo.io/ip):8080${NC}"
        echo -e "  服务管理: ${CYAN}systemctl start/stop/restart tomcat${NC}"
        echo -e "  日志查看: ${CYAN}tail -f /www/server/tomcat/logs/catalina.out${NC}"
        echo -e "  配置文件: ${CYAN}/www/server/tomcat/conf/server.xml${NC}"
        echo
        echo -e "${CYAN}使用提示：${NC}"
        echo -e "  • 默认端口8080，可在server.xml中修改"
        echo -e "  • 日志文件位于logs目录下"
    else
        echo -e "${RED}❌ Tomcat启动失败${NC}"
        echo -e "${YELLOW}请检查日志文件: /www/server/tomcat/logs/catalina.out${NC}"
        echo -e "${YELLOW}手动启动命令: /www/server/tomcat/bin/startup.sh${NC}"
        echo -e "${YELLOW}检查Java环境: java -version${NC}"
    fi
    
    echo -e "${GREEN}✅ Tomcat 9.x 安装完成！${NC}"
}

# 安装Maven
install_maven() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Maven${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Maven" "mvn" "/www/server/maven"; then
        echo -e "${YELLOW}⚠️  Maven 已安装${NC}"
        read -p "是否要卸载现有Maven？(y/n，默认n): " uninstall_maven
        if [[ $uninstall_maven =~ ^[Yy]$ ]]; then
            uninstall_component "Maven" "rm -rf /www/server/maven"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
            # 清理环境变量
            sed -i '/MAVEN_HOME/d' /etc/profile
        else
            echo -e "${YELLOW}跳过Maven安装${NC}"
            return
        fi
    fi
    
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}正在下载Maven 3.6.0...${NC}"
    wget https://archive.apache.org/dist/maven/maven-3/3.6.0/binaries/apache-maven-3.6.0-bin.tar.gz
    
    echo -e "${YELLOW}正在解压Maven...${NC}"
    tar -xzf apache-maven-3.6.0-bin.tar.gz
    mv apache-maven-3.6.0 /www/server/maven
    
    echo -e "${YELLOW}配置Maven环境变量...${NC}"
    echo 'export MAVEN_HOME=/www/server/maven' >> /etc/profile
    echo 'export PATH=$MAVEN_HOME/bin:$PATH' >> /etc/profile
    
    echo -e "${YELLOW}创建Maven本地仓库目录...${NC}"
    mkdir -p /www/server/maven/repository
    
    echo -e "${YELLOW}验证Maven安装...${NC}"
    source /etc/profile
    mvn -version
    
    echo -e "${GREEN}✅ Maven 安装完成！${NC}"
}

# 安装Nginx
install_nginx() {
    echo -e "\n${CYAN}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}                    🔧 安装Nginx${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Nginx" "nginx" ""; then
        echo -e "${YELLOW}⚠️  Nginx 已安装${NC}"
        echo -e "${YELLOW}跳过Nginx安装${NC}"
        # 自动跳转到Nginx管理面板
        echo -e "${YELLOW}正在跳转到Nginx管理面板...${NC}"
        sleep 2
        nginx_management_panel
        # 如果从管理面板返回安装页，则返回到安装导航界面
        if [ $? -eq 2 ]; then
            return 2
        fi
    fi
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔄 正在执行安装操作...${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}📋 步骤 1/5: 安装Nginx依赖...${NC}"
    yum install -y epel-release
    yum install -y nginx
    echo -e "${GREEN}✅ 依赖安装完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 2/5: 启动Nginx服务...${NC}"
    systemctl start nginx
    systemctl enable nginx
    echo -e "${GREEN}✅ 服务启动完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 3/5: 配置防火墙...${NC}"
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
    echo -e "${GREEN}✅ 防火墙配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 4/5: 验证Nginx安装...${NC}"
    nginx -v
    systemctl status nginx --no-pager
    echo -e "${GREEN}✅ 安装验证完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 5/5: 安装完成${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🎉 Nginx 安装完成！${NC}"
    
    # 自动跳转到Nginx管理面板
    echo -e "${YELLOW}正在跳转到Nginx管理面板...${NC}"
    sleep 2
    nginx_management_panel
    # 如果从管理面板返回安装页，则返回到安装导航界面
    if [ $? -eq 2 ]; then
        return 2
    fi
}

# 配置Nginx站点
configure_nginx_sites() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🌐 配置Nginx站点${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 创建配置目录结构
    mkdir -p /etc/nginx/conf.d
    mkdir -p /etc/nginx/sites-available
    mkdir -p /etc/nginx/sites-enabled
    
    # 修改nginx.conf以包含conf.d目录
    if ! grep -q "conf.d" /etc/nginx/nginx.conf; then
        echo -e "${YELLOW}更新nginx.conf配置...${NC}"
        # 查找http块并添加include指令
        if grep -q "http {" /etc/nginx/nginx.conf; then
            # 在http块的末尾添加include指令，而不是在开头
            sed -i '/^    }$/i\    include /etc/nginx/conf.d/*.conf;' /etc/nginx/nginx.conf
        fi
    fi
    
    while true; do
        echo -e "\n${CYAN}"
        show_separator
        echo -e "${WHITE}                  🌐 Nginx 站点管理${NC}"
        show_separator
        echo
        echo -e "${WHITE}🔧 站点操作：${NC}"
        format_list_item "1" "添加新站点" "创建新的网站配置"
        format_list_item "2" "查看现有站点" "查看已配置的网站列表"
        format_list_item "3" "删除站点" "删除网站配置和文件"
        format_list_item "4" "管理子配置文件" "管理独立的配置文件"
        format_list_item "5" "退出管理" "返回Nginx管理面板"
        echo
        show_separator
        read -p "请选择 [1-5]: " choice
        
        case $choice in
            1)
                add_nginx_site
                ;;
            2)
                list_nginx_sites
                ;;
            3)
                delete_nginx_site
                ;;
            4)
                manage_sub_configs
                ;;
            5)
                break
                ;;
            *)
                echo -e "${RED}❌ 无效选择${NC}"
                ;;
        esac
    done
    
    # 测试配置并重载
    reload_nginx_config "配置更新"
}

# 添加Nginx站点
add_nginx_site() {
    echo -e "\n${YELLOW}"
    show_separator
    echo -e "${WHITE}➕ 添加新站点${NC}"
    show_separator
    
    # 输入域名
    echo -e "${CYAN}💡 域名格式说明：${NC}"
    echo -e "  • 支持格式: example.com, www.example.com, sub.example.com"
    echo -e "  • 建议使用: 小写字母、数字、连字符"
    echo -e "  • 示例: mywebsite.com, test-site.com"
    echo
    read -p "请输入域名 (回车取消): " domain
    if [ -z "$domain" ]; then
        echo -e "${YELLOW}取消添加站点${NC}"
        return
    fi
    
    # 验证域名格式
    if ! validate_domain "$domain"; then
        echo -e "${RED}❌ 域名格式无效，请使用正确的域名格式${NC}"
        echo -e "${YELLOW}示例: example.com, test-site.com${NC}"
        return
    fi
    
    # 检查站点目录是否已存在
    local default_site_root="/www/wwwroot/$domain"
    if [ -d "$default_site_root" ]; then
        echo -e "${YELLOW}⚠️  站点目录已存在: $default_site_root${NC}"
        echo -e "${WHITE}目录内容：${NC}"
        ls -la "$default_site_root" | head -10
        
        echo -e "\n${CYAN}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}                📁 目录选择${NC}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo
        echo -e "${WHITE}🔧 目录操作：${NC}"
        echo -e "${CYAN}1.${NC} ${WHITE}使用现有目录${NC}                ${CYAN}3.${NC} ${WHITE}取消操作${NC}"
        echo -e "${CYAN}2.${NC} ${WHITE}删除现有目录后重新创建${NC}"
        echo
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        read -p "请选择 [1-3]: " dir_choice
        
        case $dir_choice in
            1)
                echo -e "${GREEN}✅ 将使用现有目录: $default_site_root${NC}"
                ;;
            2)
                echo -e "${YELLOW}删除现有目录...${NC}"
                rm -rf "$default_site_root"
                mkdir -p "$default_site_root"
                echo -e "${GREEN}✅ 目录已重新创建${NC}"
                ;;
            3)
                echo -e "${YELLOW}取消操作${NC}"
                return
                ;;
            *)
                echo -e "${RED}❌ 无效选择，取消操作${NC}"
                return
                ;;
        esac
    fi
    
    # 检查域名配置文件是否已存在
    if [ -f "/etc/nginx/conf.d/$domain.conf" ] || [ -f "/etc/nginx/sites-available/$domain.conf" ]; then
        echo -e "${YELLOW}⚠️  域名配置文件已存在${NC}"
        if [ -f "/etc/nginx/conf.d/$domain.conf" ]; then
            echo -e "${WHITE}发现配置文件: /etc/nginx/conf.d/$domain.conf${NC}"
        fi
        if [ -f "/etc/nginx/sites-available/$domain.conf" ]; then
            echo -e "${WHITE}发现配置文件: /etc/nginx/sites-available/$domain.conf${NC}"
        fi
        
        echo -e "\n${CYAN}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}                ⚙️  配置选择${NC}"
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo
        echo -e "${WHITE}🔧 配置操作：${NC}"
        echo -e "${CYAN}1.${NC} ${WHITE}覆盖现有配置${NC}                ${CYAN}2.${NC} ${WHITE}取消操作${NC}"
        echo
        echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        read -p "请选择 [1-2]: " config_choice
        
        case $config_choice in
            1)
                echo -e "${YELLOW}将覆盖现有配置...${NC}"
                ;;
            2)
                echo -e "${YELLOW}取消操作${NC}"
                return
                ;;
            *)
                echo -e "${RED}❌ 无效选择，取消操作${NC}"
                return
                ;;
        esac
    fi
    
    # 选择站点类型
    echo -e "\n${CYAN}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}                🌐 站点类型选择${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    echo -e "${WHITE}🔧 站点类型说明：${NC}"
    echo -e "${CYAN}1.${NC} ${WHITE}静态网站${NC} - HTML/CSS/JS文件，适合前端项目"
    echo -e "${CYAN}2.${NC} ${WHITE}反向代理${NC} - 转发到其他服务器，适合后端API"
    echo -e "${CYAN}3.${NC} ${WHITE}PHP网站${NC} - 动态网站，需要PHP环境"
    echo
    echo -e "${YELLOW}💡 推荐选择：${NC}"
    echo -e "  • 个人博客/企业官网: 选择 ${CYAN}静态网站${NC}"
    echo -e "  • 前端项目/单页应用: 选择 ${CYAN}静态网站${NC}"
    echo -e "  • 后端API/微服务: 选择 ${CYAN}反向代理${NC}"
    echo -e "  • WordPress/动态网站: 选择 ${CYAN}PHP网站${NC}"
    echo
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    read -p "请选择站点类型 [1-3，回车默认1]: " site_type
    site_type=${site_type:-"1"}
    
    # 选择配置方式
    echo -e "\n${CYAN}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}                ⚙️  配置方式选择${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    echo -e "${WHITE}🔧 配置方式说明：${NC}"
    echo -e "${CYAN}1.${NC} ${WHITE}直接配置（推荐）${NC} - 自动生效，适合大多数用户"
    echo -e "${CYAN}2.${NC} ${WHITE}子配置文件${NC} - 需要手动导入，适合高级用户"
    echo
    echo -e "${YELLOW}💡 推荐选择：${NC}"
    echo -e "  • 新手用户/快速部署: 选择 ${CYAN}直接配置${NC}"
    echo -e "  • 高级用户/自定义配置: 选择 ${CYAN}子配置文件${NC}"
    echo
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    read -p "请选择配置方式 [1-2，回车默认1]: " config_type
    config_type=${config_type:-"1"}
    
    case $site_type in
        1)
            configure_static_site "$domain" "$config_type"
            ;;
        2)
            configure_proxy_site "$domain" "$config_type"
            ;;
        3)
            configure_php_site "$domain" "$config_type"
            ;;
        *)
            echo -e "${RED}❌ 无效选择${NC}"
            return
            ;;
    esac
    
    # 启用站点
    enable_nginx_site "$domain" "$config_type"
}

# 配置静态网站
configure_static_site() {
    local domain="$1"
    local config_type="$2"
    
    # 输入网站根目录
    echo -e "\n${CYAN}📁 网站目录配置${NC}"
    echo -e "${YELLOW}💡 目录说明：${NC}"
    echo -e "  • 这是存放网站文件的主目录"
    echo -e "  • 建议使用默认路径，便于管理"
    echo -e "  • 确保目录有足够的磁盘空间"
    echo
    read -p "请输入网站根目录 (回车使用默认: /www/wwwroot/$domain): " site_root
    site_root=${site_root:-"/www/wwwroot/$domain"}
    
    # 检查目录是否存在，如果不存在则创建
    if [ ! -d "$site_root" ]; then
        echo -e "${YELLOW}创建目录: $site_root${NC}"
        mkdir -p "$site_root"
    else
        echo -e "${GREEN}✅ 使用现有目录: $site_root${NC}"
    fi
    
    # 根据配置类型选择保存位置
    if [ "$config_type" = "2" ]; then
        # 子配置文件
        config_file="/etc/nginx/sites-available/$domain.conf"
        echo -e "${YELLOW}生成子配置文件: $config_file${NC}"
    else
        # 直接配置
        config_file="/etc/nginx/conf.d/$domain.conf"
        echo -e "${YELLOW}生成直接配置文件: $config_file${NC}"
    fi
    
    # 生成配置文件
    cat > "$config_file" << EOF
server {
    listen 80;
    server_name $domain www.$domain;
    root $site_root;
    index index.html index.htm index.php;
    
    # 日志配置
    access_log /var/log/nginx/$domain.access.log;
    error_log /var/log/nginx/$domain.error.log;
    
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 主页面
    location / {
        try_files \$uri \$uri/ /index.html;
    }
    
    # 安全配置
    location ~ /\. {
        deny all;
    }
    
    # 禁止访问敏感文件
    location ~* \.(htaccess|htpasswd|ini|log|sh|sql|conf)$ {
        deny all;
    }
}
EOF
    
    echo -e "${GREEN}✅ 静态网站配置完成${NC}"
    echo -e "${CYAN}网站根目录: $site_root${NC}"
    
    # 创建欢迎页面
    create_welcome_page "$domain" "$site_root"
}

# 配置反向代理
configure_proxy_site() {
    local domain="$1"
    local config_type="$2"
    
    # 输入代理目标
    echo -e "\n${CYAN}🌐 代理目标配置${NC}"
    echo -e "${YELLOW}💡 代理目标说明：${NC}"
    echo -e "  • 这是您的后端服务地址"
    echo -e "  • 格式: http://IP:端口 或 https://IP:端口"
    echo -e "  • 示例: http://127.0.0.1:8080, http://192.168.1.100:3000"
    echo
    read -p "请输入代理目标 (回车取消): " proxy_target
    if [ -z "$proxy_target" ]; then
        echo -e "${YELLOW}取消配置代理站点${NC}"
        return
    fi
    
    # 验证代理目标格式
    if [[ ! "$proxy_target" =~ ^https?://[^:]+:[0-9]+ ]]; then
        echo -e "${RED}❌ 代理目标格式无效，请使用 http://IP:端口 格式${NC}"
        echo -e "${YELLOW}示例: http://127.0.0.1:8080${NC}"
        return
    fi
    
    # 输入代理路径
    echo -e "\n${CYAN}📂 代理路径配置${NC}"
    echo -e "${YELLOW}💡 代理路径说明：${NC}"
    echo -e "  • 这是访问代理的URL路径"
    echo -e "  • 默认 / 表示根路径"
    echo -e "  • 示例: /api 表示只代理 /api 开头的请求"
    echo
    read -p "请输入代理路径 (回车使用默认: /): " proxy_path
    proxy_path=${proxy_path:-"/"}
    
    # 根据配置类型选择保存位置
    if [ "$config_type" = "2" ]; then
        # 子配置文件
        config_file="/etc/nginx/sites-available/$domain.conf"
        echo -e "${YELLOW}生成子配置文件: $config_file${NC}"
    else
        # 直接配置
        config_file="/etc/nginx/conf.d/$domain.conf"
        echo -e "${YELLOW}生成直接配置文件: $config_file${NC}"
    fi
    
    # 生成配置文件
    cat > "$config_file" << EOF
server {
    listen 80;
    server_name $domain www.$domain;
    
    # 日志配置
    access_log /var/log/nginx/$domain.access.log;
    error_log /var/log/nginx/$domain.error.log;
    
    # 反向代理配置
    location $proxy_path {
        proxy_pass $proxy_target;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        # 超时配置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # 缓冲配置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
    
    # 静态文件直接访问（可选）
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
EOF
    
    echo -e "${GREEN}✅ 反向代理配置完成${NC}"
    echo -e "${CYAN}代理目标: $proxy_target${NC}"
    echo -e "${CYAN}代理路径: $proxy_path${NC}"
}

# 配置PHP网站
configure_php_site() {
    local domain="$1"
    local config_type="$2"
    
    # 输入网站根目录
    echo -e "\n${CYAN}📁 PHP网站目录配置${NC}"
    echo -e "${YELLOW}💡 目录说明：${NC}"
    echo -e "  • 这是存放PHP网站文件的主目录"
    echo -e "  • 建议使用默认路径，便于管理"
    echo -e "  • 确保PHP-FPM已安装并运行在127.0.0.1:9000"
    echo -e "  • 支持WordPress、Laravel等PHP框架"
    echo
    read -p "请输入网站根目录 (回车使用默认: /www/wwwroot/$domain): " site_root
    site_root=${site_root:-"/www/wwwroot/$domain"}
    
    # 检查目录是否存在，如果不存在则创建
    if [ ! -d "$site_root" ]; then
        echo -e "${YELLOW}创建目录: $site_root${NC}"
        mkdir -p "$site_root"
    else
        echo -e "${GREEN}✅ 使用现有目录: $site_root${NC}"
    fi
    
    # 根据配置类型选择保存位置
    if [ "$config_type" = "2" ]; then
        # 子配置文件
        config_file="/etc/nginx/sites-available/$domain.conf"
        echo -e "${YELLOW}生成子配置文件: $config_file${NC}"
    else
        # 直接配置
        config_file="/etc/nginx/conf.d/$domain.conf"
        echo -e "${YELLOW}生成直接配置文件: $config_file${NC}"
    fi
    
    # 生成配置文件
    cat > "$config_file" << EOF
server {
    listen 80;
    server_name $domain www.$domain;
    root $site_root;
    index index.php index.html index.htm;
    
    # 日志配置
    access_log /var/log/nginx/$domain.access.log;
    error_log /var/log/nginx/$domain.error.log;
    
    # PHP配置
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
        
        # 超时配置
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
    }
    
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # 主页面
    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }
    
    # 安全配置
    location ~ /\. {
        deny all;
    }
    
    # 禁止访问敏感文件
    location ~* \.(htaccess|htpasswd|ini|log|sh|sql|conf)$ {
        deny all;
    }
}
EOF
    
    echo -e "${GREEN}✅ PHP网站配置完成${NC}"
    echo -e "${CYAN}网站根目录: $site_root${NC}"
    echo -e "${YELLOW}注意: 请确保PHP-FPM已安装并运行在127.0.0.1:9000${NC}"
}

# 重载Nginx配置
reload_nginx_config() {
    local operation="$1"
    local force_restart="$2"
    
    echo -e "${YELLOW}🔍 正在测试Nginx配置...${NC}"
    if nginx -t >/dev/null 2>&1; then
        if [ "$force_restart" = "true" ]; then
            echo -e "${YELLOW}🔄 正在重启Nginx服务...${NC}"
            if systemctl restart nginx >/dev/null 2>&1; then
                echo -e "${GREEN}✅ Nginx服务重启成功！${operation}已生效${NC}"
                echo -e "${CYAN}💡 服务状态：${NC}"
                systemctl is-active --quiet nginx && echo -e "  ${GREEN}✅ 运行中${NC}" || echo -e "  ${RED}❌ 已停止${NC}"
                return 0
            else
                echo -e "${RED}❌ Nginx服务重启失败${NC}"
                echo -e "${YELLOW}🔧 故障排除：${NC}"
                echo -e "  • 检查配置: nginx -t"
                echo -e "  • 查看日志: journalctl -u nginx"
                echo -e "  • 手动重启: systemctl restart nginx"
                return 1
            fi
        else
            echo -e "${YELLOW}🔄 正在重载Nginx配置...${NC}"
            if systemctl reload nginx >/dev/null 2>&1; then
                echo -e "${GREEN}✅ Nginx配置重载成功！${operation}已生效${NC}"
                echo -e "${CYAN}💡 重载说明：${NC}"
                echo -e "  • 配置已更新，无需重启服务"
                echo -e "  • 现有连接不受影响"
                echo -e "  • 新请求将使用新配置"
                return 0
            else
                echo -e "${RED}❌ Nginx配置重载失败${NC}"
                echo -e "${YELLOW}🔧 故障排除：${NC}"
                echo -e "  • 检查配置: nginx -t"
                echo -e "  • 查看日志: journalctl -u nginx"
                echo -e "  • 手动重载: systemctl reload nginx"
                return 1
            fi
        fi
    else
        echo -e "${RED}❌ Nginx配置测试失败${NC}"
        echo -e "${YELLOW}🔧 故障排除：${NC}"
        echo -e "  • 手动测试: nginx -t"
        echo -e "  • 检查语法错误"
        echo -e "  • 查看详细错误信息"
        return 1
    fi
}

# 启用Nginx站点
enable_nginx_site() {
    local domain="$1"
    local config_type="$2"
    
    if [ "$config_type" = "2" ]; then
        # 子配置文件需要手动导入
        if [ -f "/etc/nginx/sites-available/$domain.conf" ]; then
            echo -e "${GREEN}✅ 子配置文件已生成${NC}"
            echo -e "${CYAN}📁 配置文件位置: /etc/nginx/sites-available/$domain.conf${NC}"
            echo -e "${YELLOW}⚠️  注意: 子配置文件需要手动导入到主配置中${NC}"
            echo -e "${CYAN}🔧 导入方法: 在nginx.conf的http块中添加:${NC}"
            echo -e "${WHITE}    include /etc/nginx/sites-available/$domain.conf;${NC}"
            echo -e "${CYAN}💡 导入后需要重载Nginx配置${NC}"
        else
            echo -e "${RED}❌ 子配置文件生成失败${NC}"
        fi
    else
        # 直接配置文件自动生效
        if [ -f "/etc/nginx/conf.d/$domain.conf" ]; then
            echo -e "${GREEN}✅ 站点 $domain 已启用${NC}"
            echo -e "${CYAN}📁 配置文件位置: /etc/nginx/conf.d/$domain.conf${NC}"
            
            # 自动测试配置并重载Nginx
            echo -e "${YELLOW}🔄 正在应用配置...${NC}"
            reload_nginx_config "站点启用"
            if [ $? -eq 0 ]; then
                echo -e "${CYAN}🌐 访问信息：${NC}"
                echo -e "  • 访问地址: ${CYAN}http://$domain${NC}"
                echo -e "  • 本地测试: ${CYAN}http://localhost${NC}"
                echo -e "  • 外网访问: ${CYAN}http://$(curl -s ipinfo.io/ip)${NC}"
                echo -e "${CYAN}💡 提示：${NC}"
                echo -e "  • 确保域名已正确解析到服务器IP"
                echo -e "  • 如果无法访问，请检查防火墙设置"
                echo -e "  • 查看访问日志: tail -f /var/log/nginx/$domain.access.log"
            fi
        else
            echo -e "${RED}❌ 站点 $domain 配置文件不存在${NC}"
            echo -e "${YELLOW}🔧 故障排除：${NC}"
            echo -e "  • 检查配置文件路径"
            echo -e "  • 确认配置生成过程"
        fi
    fi
}

# 验证站点删除效果
verify_site_deletion() {
    local domain="$1"
    
    echo -e "${YELLOW}正在验证站点删除效果...${NC}"
    
    # 检查配置文件是否存在
    if [ -f "/etc/nginx/conf.d/$domain.conf" ]; then
        echo -e "${RED}❌ 配置文件仍存在: /etc/nginx/conf.d/$domain.conf${NC}"
        return 1
    else
        echo -e "${GREEN}✅ 配置文件已删除${NC}"
    fi
    
    # 检查Nginx进程是否包含该域名
    if pgrep -f "nginx" > /dev/null; then
        local nginx_processes=$(ps aux | grep nginx | grep -v grep)
        if echo "$nginx_processes" | grep -q "$domain"; then
            echo -e "${RED}❌ Nginx进程仍包含域名: $domain${NC}"
            return 1
        else
            echo -e "${GREEN}✅ Nginx进程已清理${NC}"
        fi
    fi
    
    # 检查端口监听
    if netstat -tlnp 2>/dev/null | grep -q ":80.*nginx"; then
        echo -e "${GREEN}✅ Nginx仍在监听80端口${NC}"
    else
        echo -e "${YELLOW}⚠️  Nginx未监听80端口${NC}"
    fi
    
    return 0
}

# 列出Nginx站点
list_nginx_sites() {
    echo -e "\n${YELLOW}"
    show_separator
    echo -e "${WHITE}📋 现有站点列表${NC}"
    show_separator
    
    if [ -z "$(ls -A /etc/nginx/conf.d/*.conf 2>/dev/null)" ]; then
        echo -e "${YELLOW}暂无配置的站点${NC}"
        return
    fi
    
    echo -e "${WHITE}已配置的站点：${NC}"
    local i=1
    for config in /etc/nginx/conf.d/*.conf; do
        if [ -f "$config" ]; then
            domain=$(basename "$config" .conf)
            status="${GREEN}✅ 已启用${NC}"
            echo -e "  ${CYAN}$i.${NC} ${CYAN}$domain${NC} - $status"
            echo -e "    配置文件: $config"
            ((i++))
        fi
    done
}

# 删除Nginx站点
delete_nginx_site() {
    echo -e "\n${YELLOW}"
    show_separator
    echo -e "${WHITE}🗑️  删除站点${NC}"
    show_separator
    
    # 检查是否有站点配置
    if [ -z "$(ls -A /etc/nginx/conf.d/*.conf 2>/dev/null)" ]; then
        echo -e "${YELLOW}暂无配置的站点${NC}"
        return
    fi
    
    # 列出可用站点
    list_nginx_sites
    
    # 创建站点数组
    local sites=()
    for config in /etc/nginx/conf.d/*.conf; do
        if [ -f "$config" ]; then
            sites+=("$(basename "$config" .conf)")
        fi
    done
    
    read -p "请选择要删除的站点编号 [1-${#sites[@]}]: " site_choice
    
    if ! [[ "$site_choice" =~ ^[0-9]+$ ]] || [ "$site_choice" -lt 1 ] || [ "$site_choice" -gt ${#sites[@]} ]; then
        echo -e "${RED}❌ 无效的选择${NC}"
        return
    fi
    
    domain="${sites[$((site_choice-1))]}"
    
    read -p "确认删除站点 $domain？(y/n，默认n): " confirm
    if [[ $confirm =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}正在彻底删除站点 $domain...${NC}"
        
        # 1. 删除配置文件
        rm -f "/etc/nginx/conf.d/$domain.conf"
        echo -e "${GREEN}✅ 配置文件已删除${NC}"
        
        # 2. 删除网站目录（可选）
        read -p "是否同时删除网站目录 /www/wwwroot/$domain？(y/n，默认n): " delete_dir
        if [[ $delete_dir =~ ^[Yy]$ ]]; then
            rm -rf "/www/wwwroot/$domain"
            echo -e "${GREEN}✅ 网站目录已删除${NC}"
        fi
        
        # 3. 清理日志文件
        rm -f "/var/log/nginx/$domain.access.log"
        rm -f "/var/log/nginx/$domain.error.log"
        echo -e "${GREEN}✅ 日志文件已清理${NC}"
        
        # 4. 清理Nginx缓存
        rm -rf /var/cache/nginx/* 2>/dev/null
        echo -e "${GREEN}✅ Nginx缓存已清理${NC}"
        
        # 5. 强制重启Nginx以确保配置完全生效
        echo -e "${YELLOW}正在强制重启Nginx以确保删除生效...${NC}"
        reload_nginx_config "站点删除" "true"
        
        # 6. 验证删除结果
        echo -e "${YELLOW}正在验证删除结果...${NC}"
        verify_site_deletion "$domain"
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}✅ 站点 $domain 删除完成！${NC}"
            echo -e "${CYAN}提示：如果浏览器仍能访问，请清除浏览器缓存或等待DNS缓存过期${NC}"
            echo -e "${YELLOW}清除浏览器缓存方法：${NC}"
            echo -e "  • Chrome/Edge: Ctrl+Shift+Delete"
            echo -e "  • Firefox: Ctrl+Shift+Delete"
            echo -e "  • Safari: Cmd+Option+E"
        else
            echo -e "${RED}❌ 站点删除验证失败${NC}"
        fi
    else
        echo -e "${YELLOW}取消删除${NC}"
    fi
}

# 管理子配置文件
manage_sub_configs() {
    echo -e "\n${YELLOW}"
    show_separator
    echo -e "${WHITE}📁 管理子配置文件${NC}"
    show_separator
    
    while true; do
        echo -e "\n${CYAN}"
        show_separator
        echo -e "${WHITE}                📁 子配置文件管理${NC}"
        show_separator
        echo
        echo -e "${WHITE}🔧 配置操作：${NC}"
        format_list_item "1" "查看子配置文件" "查看sites-available目录下的配置"
        format_list_item "2" "导入子配置文件" "将配置导入到主配置中"
        format_list_item "3" "导出子配置文件" "导出配置文件到指定位置"
        format_list_item "4" "删除子配置文件" "删除不需要的配置文件"
        format_list_item "5" "返回上级" "返回站点管理面板"
        echo
        show_separator
        read -p "请选择 [1-5]: " sub_choice
        
        case $sub_choice in
            1)
                list_sub_configs
                ;;
            2)
                import_sub_config
                ;;
            3)
                export_sub_config
                ;;
            4)
                delete_sub_config
                ;;
            5)
                break
                ;;
            *)
                echo -e "${RED}❌ 无效选择${NC}"
                ;;
        esac
    done
}

# 列出子配置文件
list_sub_configs() {
    echo -e "\n${WHITE}子配置文件列表：${NC}"
    
    if [ -z "$(ls -A /etc/nginx/sites-available/*.conf 2>/dev/null)" ]; then
        echo -e "${YELLOW}暂无子配置文件${NC}"
        return
    fi
    
    for config in /etc/nginx/sites-available/*.conf; do
        if [ -f "$config" ]; then
            domain=$(basename "$config" .conf)
            echo -e "  ${CYAN}$domain${NC} - $config"
        fi
    done
}

# 导入子配置文件
import_sub_config() {
    echo -e "\n${WHITE}导入子配置文件到主配置：${NC}"
    
    # 列出可用的子配置文件
    list_sub_configs
    
    read -p "请输入要导入的域名: " domain
    if [ -z "$domain" ]; then
        echo -e "${RED}❌ 域名不能为空${NC}"
        return
    fi
    
    if [ ! -f "/etc/nginx/sites-available/$domain.conf" ]; then
        echo -e "${RED}❌ 子配置文件不存在${NC}"
        return
    fi
    
    # 检查是否已经导入
    if grep -q "include /etc/nginx/sites-available/$domain.conf;" /etc/nginx/nginx.conf; then
        echo -e "${YELLOW}⚠️  该子配置文件已经导入${NC}"
        return
    fi
    
    # 导入到nginx.conf
    echo -e "${YELLOW}正在导入子配置文件...${NC}"
    sed -i '/http {/a\    include /etc/nginx/sites-available/'$domain'.conf;' /etc/nginx/nginx.conf
    
    echo -e "${GREEN}✅ 子配置文件已导入${NC}"
    echo -e "${CYAN}导入位置: /etc/nginx/nginx.conf${NC}"
    
    # 自动测试配置并重载Nginx
    reload_nginx_config "子配置文件导入"
}

# 导出子配置文件
export_sub_config() {
    echo -e "\n${WHITE}导出子配置文件：${NC}"
    
    # 列出可用的子配置文件
    list_sub_configs
    
    read -p "请输入要导出的域名: " domain
    if [ -z "$domain" ]; then
        echo -e "${RED}❌ 域名不能为空${NC}"
        return
    fi
    
    if [ ! -f "/etc/nginx/sites-available/$domain.conf" ]; then
        echo -e "${RED}❌ 子配置文件不存在${NC}"
        return
    fi
    
    # 创建导出目录
    export_dir="/tmp/nginx_configs_$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$export_dir"
    
    # 复制配置文件
    cp "/etc/nginx/sites-available/$domain.conf" "$export_dir/"
    
    echo -e "${GREEN}✅ 子配置文件已导出${NC}"
    echo -e "${CYAN}导出位置: $export_dir/$domain.conf${NC}"
}

# 删除子配置文件
delete_sub_config() {
    echo -e "\n${WHITE}删除子配置文件：${NC}"
    
    # 列出可用的子配置文件
    list_sub_configs
    
    read -p "请输入要删除的域名: " domain
    if [ -z "$domain" ]; then
        echo -e "${RED}❌ 域名不能为空${NC}"
        return
    fi
    
    if [ ! -f "/etc/nginx/sites-available/$domain.conf" ]; then
        echo -e "${RED}❌ 子配置文件不存在${NC}"
        return
    fi
    
    read -p "确认删除子配置文件 $domain？(y/n，默认n): " confirm
    if [[ $confirm =~ ^[Yy]$ ]]; then
        # 从nginx.conf中移除include
        sed -i '/include \/etc\/nginx\/sites-available\/'$domain'\.conf;/d' /etc/nginx/nginx.conf
        
        # 删除配置文件
        rm -f "/etc/nginx/sites-available/$domain.conf"
        
        echo -e "${GREEN}✅ 子配置文件已删除${NC}"
        
        # 自动测试配置并重载Nginx
        reload_nginx_config "子配置文件删除" "true"
    else
        echo -e "${YELLOW}取消删除${NC}"
    fi
}

# Nginx管理面板
nginx_management_panel() {
    while true; do
        clear
        echo -e "${CYAN}"
        show_separator
        echo -e "${WHITE}                    🌐 Nginx 管理面板${NC}"
        show_separator
        echo
        
        # 显示Nginx状态
        display_nginx_status
        echo
        
        echo -e "${WHITE}🔧 管理功能：${NC}"
        echo -e "${CYAN}1.${NC} ${WHITE}站点管理${NC}              ${CYAN}6.${NC} ${WHITE}配置管理${NC}"
        echo -e "${CYAN}2.${NC} ${WHITE}服务管理${NC}              ${CYAN}7.${NC} ${WHITE}访问日志${NC}"
        echo -e "${CYAN}3.${NC} ${WHITE}SSL证书管理${NC}           ${CYAN}8.${NC} ${WHITE}性能优化${NC}"
        echo -e "${CYAN}4.${NC} ${WHITE}防火墙配置${NC}            ${CYAN}9.${NC} ${WHITE}备份/恢复${NC}"
        echo -e "${CYAN}5.${NC} ${WHITE}安全设置${NC}              ${CYAN}10.${NC} ${WHITE}配置检查/修复${NC}"
        echo -e "${CYAN}11.${NC} ${WHITE}缓存清理${NC}              ${CYAN}12.${NC} ${WHITE}卸载Nginx服务${NC}"
        echo -e "${CYAN}0.${NC} ${WHITE}返回安装页${NC}"
        echo
        show_separator
        read -p "请选择 [0-12]: " choice
        
        case $choice in
            1)
                configure_nginx_sites
                ;;
            2)
                nginx_service_management
                ;;
            3)
                nginx_ssl_management
                ;;
            4)
                nginx_firewall_config
                ;;
            5)
                nginx_security_settings
                ;;
            6)
                nginx_config_viewer
                ;;
            7)
                nginx_log_viewer
                ;;
            8)
                nginx_performance_optimization
                ;;
            9)
                nginx_backup_restore
                ;;
            10)
                nginx_config_check_fix
                ;;
            11)
                nginx_cache_cleanup
                ;;
            12)
                nginx_uninstall
                ;;
            0)
                echo -e "${YELLOW}返回安装页...${NC}"
                return 2
                ;;
            *)
                echo -e "${RED}❌ 无效选择${NC}"
                sleep 2
                ;;
        esac
    done
}

# Nginx服务管理
nginx_service_management() {
    while true; do
        clear
        echo -e "${CYAN}"
        show_separator
        echo -e "${WHITE}                  ⚙️  Nginx 服务管理${NC}"
        show_separator
        echo
        
        # 显示Nginx状态
        display_nginx_status
        echo
        
        echo -e "${WHITE}🔧 服务操作：${NC}"
        format_list_item "1" "启动服务" "启动Nginx服务"
        format_list_item "2" "停止服务" "停止Nginx服务"
        format_list_item "3" "重启服务" "重启Nginx服务"
        format_list_item "4" "重载配置" "重新加载配置文件"
        format_list_item "5" "设置开机自启" "设置Nginx开机自动启动"
        format_list_item "6" "取消开机自启" "取消Nginx开机自动启动"
        format_list_item "7" "查看服务状态" "查看详细的服务状态信息"
        format_list_item "8" "卸载服务" "完全卸载Nginx服务"
        format_list_item "0" "返回上级" "返回Nginx管理面板"
        echo
        show_separator
        read -p "请选择操作 [0-8]: " service_choice
        
        case $service_choice in
            1)
                systemctl start nginx
                echo -e "${GREEN}✅ Nginx已启动${NC}"
                ;;
            2)
                systemctl stop nginx
                echo -e "${YELLOW}⚠️  Nginx已停止${NC}"
                ;;
            3)
                systemctl restart nginx
                echo -e "${GREEN}✅ Nginx已重启${NC}"
                ;;
            4)
                reload_nginx_config "配置重载"
                ;;
            5)
                systemctl enable nginx
                echo -e "${GREEN}✅ 已设置开机自启${NC}"
                ;;
            6)
                systemctl disable nginx
                echo -e "${YELLOW}⚠️  已取消开机自启${NC}"
                ;;
            7)
                systemctl status nginx --no-pager
                ;;
            8)
                nginx_uninstall
                ;;
            0)
                break
                ;;
            *)
                echo -e "${RED}❌ 无效选择${NC}"
                ;;
        esac
        
        echo -e "\n${YELLOW}按回车键继续...${NC}"
        read
    done
}

# Nginx缓存清理
nginx_cache_cleanup() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}🧹 Nginx 缓存清理${NC}"
    show_separator
    
    echo -e "${YELLOW}正在清理Nginx缓存...${NC}"
    
    # 1. 清理Nginx缓存目录
    if [ -d "/var/cache/nginx" ]; then
        rm -rf /var/cache/nginx/*
        echo -e "${GREEN}✅ Nginx缓存目录已清理${NC}"
    else
        echo -e "${YELLOW}⚠️  Nginx缓存目录不存在${NC}"
    fi
    
    # 2. 清理临时文件
    rm -rf /tmp/nginx_* 2>/dev/null
    echo -e "${GREEN}✅ 临时文件已清理${NC}"
    
    # 3. 清理日志缓存
    if [ -d "/var/log/nginx" ]; then
        find /var/log/nginx -name "*.log.*" -delete 2>/dev/null
        echo -e "${GREEN}✅ 日志缓存已清理${NC}"
    fi
    
    # 4. 重启Nginx以确保缓存完全清理
    echo -e "${YELLOW}正在重启Nginx以确保缓存完全清理...${NC}"
    systemctl restart nginx
    
    if systemctl is-active --quiet nginx; then
        echo -e "${GREEN}✅ Nginx重启成功，缓存清理完成！${NC}"
        echo -e "${CYAN}提示：现在可以清除浏览器缓存并重新测试访问${NC}"
    else
        echo -e "${RED}❌ Nginx重启失败${NC}"
        echo -e "${YELLOW}请手动执行: systemctl restart nginx${NC}"
    fi
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx卸载
nginx_uninstall() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                    🗑️  Nginx 卸载${NC}"
    show_separator
    echo
    echo -e "${RED}⚠️  警告：此操作将完全卸载Nginx及其配置文件${NC}"
    echo -e "${YELLOW}⚠️  请确保您已备份重要的配置文件${NC}"
    echo
    show_separator
    
    read -p "确认要卸载Nginx？(y/n，默认n): " confirm_uninstall
    if [[ ! $confirm_uninstall =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}取消卸载操作${NC}"
        return
    fi
    
    show_separator
    echo -e "${WHITE}🔄 正在执行卸载操作...${NC}"
    show_separator
    
    echo -e "${YELLOW}📋 步骤 1/6: 正在停止Nginx服务...${NC}"
    systemctl stop nginx 2>/dev/null
    systemctl disable nginx 2>/dev/null
    echo -e "${GREEN}✅ 服务已停止${NC}"
    
    echo -e "${YELLOW}📋 步骤 2/6: 正在卸载Nginx软件包...${NC}"
    yum remove -y nginx 2>/dev/null
    echo -e "${GREEN}✅ 软件包已卸载${NC}"
    
    echo -e "${YELLOW}📋 步骤 3/6: 正在清理Nginx配置文件...${NC}"
    rm -rf /etc/nginx
    rm -rf /var/log/nginx
    rm -rf /var/cache/nginx
    echo -e "${GREEN}✅ 配置文件已清理${NC}"
    
    echo -e "${YELLOW}📋 步骤 4/6: 正在清理Nginx用户和组...${NC}"
    userdel nginx 2>/dev/null
    groupdel nginx 2>/dev/null
    echo -e "${GREEN}✅ 用户和组已清理${NC}"
    
    echo -e "${YELLOW}📋 步骤 5/6: 正在清理防火墙规则...${NC}"
    firewall-cmd --permanent --remove-service=http 2>/dev/null
    firewall-cmd --permanent --remove-service=https 2>/dev/null
    firewall-cmd --reload 2>/dev/null
    echo -e "${GREEN}✅ 防火墙规则已清理${NC}"
    
    echo -e "${YELLOW}📋 步骤 6/6: 卸载完成${NC}"
    show_separator
    echo -e "${GREEN}🎉 Nginx 卸载完成！${NC}"
    echo -e "${YELLOW}💡 注意：网站文件未删除，如需清理请手动删除${NC}"
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx SSL证书管理
nginx_ssl_management() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                🔒 SSL 证书管理${NC}"
    show_separator
    echo
    echo -e "${YELLOW}⚠️  功能正在开发中...${NC}"
    echo
    echo -e "${WHITE}🔧 计划功能：${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Let's Encrypt 自动证书申请${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}手动证书上传${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}证书续期管理${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}SSL配置优化${NC}"
    echo
    show_separator
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx防火墙配置
nginx_firewall_config() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}🔥 Nginx 防火墙配置${NC}"
    show_separator
    
    echo -e "${WHITE}📊 当前防火墙状态：${NC}"
    if systemctl is-active --quiet firewalld; then
        echo -e "${GREEN}✅ firewalld 运行中${NC}"
        
        echo -e "\n${WHITE}🌐 已开放的端口：${NC}"
        local open_ports=$(firewall-cmd --list-ports 2>/dev/null)
        if [ -n "$open_ports" ]; then
            echo "$open_ports"
        else
            echo -e "${YELLOW}暂无开放端口${NC}"
        fi
        
        echo -e "\n${WHITE}🔧 已开放的服务：${NC}"
        local open_services=$(firewall-cmd --list-services 2>/dev/null)
        if [ -n "$open_services" ]; then
            echo "$open_services"
        else
            echo -e "${YELLOW}暂无开放服务${NC}"
        fi
        
        echo -e "\n${CYAN}"
        show_separator
        echo -e "${WHITE}                🔥 防火墙配置操作${NC}"
        show_separator
        echo
        echo -e "${WHITE}🔧 端口操作：${NC}"
        format_list_item "1" "开放HTTP端口(80)" "网站访问必需端口"
        format_list_item "2" "开放HTTPS端口(443)" "SSL证书必需端口"
        format_list_item "3" "开放自定义端口" "其他服务端口配置"
        format_list_item "4" "移除端口" "关闭不需要的端口"
        format_list_item "5" "一键开放Nginx端口" "自动开放80和443端口"
        echo
        echo -e "${YELLOW}💡 推荐操作：${NC}"
        echo -e "  • 首次配置: 选择 ${CYAN}5${NC} 一键开放Nginx端口"
        echo -e "  • 手动配置: 选择 ${CYAN}1${NC} 和 ${CYAN}2${NC} 分别开放"
        echo
        show_separator
        read -p "请选择操作 [1-5]: " firewall_choice
        
        case $firewall_choice in
            1)
                echo -e "${YELLOW}正在开放HTTP端口(80)...${NC}"
                firewall-cmd --permanent --add-port=80/tcp
                firewall-cmd --reload
                echo -e "${GREEN}✅ HTTP端口(80)已开放${NC}"
                echo -e "${CYAN}💡 现在可以通过 http://您的IP 访问网站${NC}"
                ;;
            2)
                echo -e "${YELLOW}正在开放HTTPS端口(443)...${NC}"
                firewall-cmd --permanent --add-port=443/tcp
                firewall-cmd --reload
                echo -e "${GREEN}✅ HTTPS端口(443)已开放${NC}"
                echo -e "${CYAN}💡 配置SSL证书后可通过 https://您的IP 访问${NC}"
                ;;
            3)
                echo -e "\n${CYAN}🔌 自定义端口配置${NC}"
                echo -e "${YELLOW}💡 端口说明：${NC}"
                echo -e "  • 端口范围: 1-65535"
                echo -e "  • 常用端口: 3000(React), 8080(Tomcat), 9000(PHP-FPM)"
                echo
                read -p "请输入端口号: " custom_port
                if validate_port "$custom_port"; then
                    echo -e "${YELLOW}正在开放端口 $custom_port...${NC}"
                    firewall-cmd --permanent --add-port=$custom_port/tcp
                    firewall-cmd --reload
                    echo -e "${GREEN}✅ 端口 $custom_port 已开放${NC}"
                else
                    echo -e "${RED}❌ 端口号无效，请输入1-65535之间的数字${NC}"
                fi
                ;;
            4)
                echo -e "\n${CYAN}🗑️  移除端口配置${NC}"
                echo -e "${YELLOW}💡 移除说明：${NC}"
                echo -e "  • 移除端口后，该端口将无法从外部访问"
                echo -e "  • 请确保移除的端口不是正在使用的服务端口"
                echo
                read -p "请输入要移除的端口号: " remove_port
                if validate_port "$remove_port"; then
                    echo -e "${YELLOW}正在移除端口 $remove_port...${NC}"
                    firewall-cmd --permanent --remove-port=$remove_port/tcp
                    firewall-cmd --reload
                    echo -e "${YELLOW}⚠️  端口 $remove_port 已移除${NC}"
                else
                    echo -e "${RED}❌ 端口号无效${NC}"
                fi
                ;;
            5)
                echo -e "${YELLOW}正在一键开放Nginx端口...${NC}"
                firewall-cmd --permanent --add-port=80/tcp
                firewall-cmd --permanent --add-port=443/tcp
                firewall-cmd --reload
                echo -e "${GREEN}✅ Nginx端口已开放${NC}"
                echo -e "${CYAN}📋 已开放端口：${NC}"
                echo -e "  • ${GREEN}80端口 (HTTP)${NC}"
                echo -e "  • ${GREEN}443端口 (HTTPS)${NC}"
                echo -e "${CYAN}💡 现在可以通过 http://您的IP 访问网站${NC}"
                ;;
        esac
    else
        echo -e "${RED}❌ firewalld 未运行${NC}"
        echo -e "${YELLOW}请先启动firewalld服务${NC}"
    fi
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx安全设置
nginx_security_settings() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                🛡️  安全设置${NC}"
    show_separator
    echo
    echo -e "${YELLOW}⚠️  功能正在开发中...${NC}"
    echo
    echo -e "${WHITE}🔧 计划功能：${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}隐藏Nginx版本信息${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}配置安全头${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}限制请求频率${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}防DDoS配置${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}访问控制${NC}"
    echo
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx配置查看器
nginx_config_viewer() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}📋 Nginx 配置查看器${NC}"
    show_separator
    
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                📋 配置查看器${NC}"
    show_separator
    echo
    echo -e "${WHITE}🔧 配置查看：${NC}"
    format_list_item "1" "主配置文件" "查看nginx.conf主配置文件"
    format_list_item "2" "站点配置目录" "查看conf.d目录下的站点配置"
    format_list_item "3" "子配置文件" "查看sites-available目录配置"
    format_list_item "4" "测试配置语法" "检查Nginx配置语法是否正确"
    echo
    show_separator
    read -p "请选择 [1-4]: " config_choice
    
    case $config_choice in
        1)
            echo -e "${YELLOW}主配置文件内容：${NC}"
            cat /etc/nginx/nginx.conf | head -50
            ;;
        2)
            echo -e "${YELLOW}站点配置文件：${NC}"
            ls -la /etc/nginx/conf.d/
            if [ -n "$(ls -A /etc/nginx/conf.d/*.conf 2>/dev/null)" ]; then
                echo -e "\n${WHITE}配置文件内容：${NC}"
                for conf in /etc/nginx/conf.d/*.conf; do
                    echo -e "${CYAN}=== $conf ===${NC}"
                    cat "$conf"
                    echo
                done
            fi
            ;;
        3)
            echo -e "${YELLOW}子配置文件：${NC}"
            ls -la /etc/nginx/sites-available/
            if [ -n "$(ls -A /etc/nginx/sites-available/*.conf 2>/dev/null)" ]; then
                echo -e "\n${WHITE}配置文件内容：${NC}"
                for conf in /etc/nginx/sites-available/*.conf; do
                    echo -e "${CYAN}=== $conf ===${NC}"
                    cat "$conf"
                    echo
                done
            fi
            ;;
        4)
            echo -e "${YELLOW}测试配置语法：${NC}"
            nginx -t
            ;;
    esac
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx日志查看器
nginx_log_viewer() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}📊 Nginx 日志查看器${NC}"
    show_separator
    
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                📊 日志查看器${NC}"
    show_separator
    echo
    echo -e "${WHITE}🔧 日志查看：${NC}"
    format_list_item "1" "访问日志" "查看网站访问记录 (access.log)"
    format_list_item "2" "错误日志" "查看错误和警告信息 (error.log)"
    format_list_item "3" "实时访问日志" "实时监控访问情况"
    format_list_item "4" "实时错误日志" "实时监控错误信息"
    format_list_item "5" "站点专用日志" "查看特定站点的日志"
    echo
    echo -e "${YELLOW}💡 日志说明：${NC}"
    echo -e "  • 访问日志记录所有HTTP请求"
    echo -e "  • 错误日志记录Nginx错误和警告"
    echo -e "  • 实时日志会持续显示新内容"
    echo -e "  • 按 Ctrl+C 退出实时日志查看"
    echo
    show_separator
    read -p "请选择操作 [1-5]: " log_choice
    
            case $log_choice in
            1)
                echo -e "\n${CYAN}📋 最近50行访问日志${NC}"
                if [ -f "/var/log/nginx/access.log" ]; then
                    echo -e "${YELLOW}日志内容：${NC}"
                    tail -n 50 /var/log/nginx/access.log
                    echo -e "\n${CYAN}💡 日志格式说明：${NC}"
                    echo -e "  • IP地址 - 访问时间 - 请求方法 - 状态码 - 响应大小"
                    echo -e "  • 示例: 192.168.1.100 - [14/Dec/2024:10:30:45 +0800] - GET / 200 1234"
                else
                    echo -e "${RED}❌ 访问日志文件不存在${NC}"
                fi
                ;;
            2)
                echo -e "\n${CYAN}📋 最近50行错误日志${NC}"
                if [ -f "/var/log/nginx/error.log" ]; then
                    echo -e "${YELLOW}日志内容：${NC}"
                    tail -n 50 /var/log/nginx/error.log
                    echo -e "\n${CYAN}💡 错误级别说明：${NC}"
                    echo -e "  • [error] - 严重错误，需要立即处理"
                    echo -e "  • [warn] - 警告信息，建议检查"
                    echo -e "  • [info] - 一般信息，正常运行"
                else
                    echo -e "${RED}❌ 错误日志文件不存在${NC}"
                fi
                ;;
            3)
                echo -e "\n${CYAN}📊 实时访问日志监控${NC}"
                echo -e "${YELLOW}💡 说明：实时显示新的访问记录，按 Ctrl+C 退出${NC}"
                if [ -f "/var/log/nginx/access.log" ]; then
                    tail -f /var/log/nginx/access.log
                else
                    echo -e "${RED}❌ 访问日志文件不存在${NC}"
                fi
                ;;
            4)
                echo -e "\n${CYAN}📊 实时错误日志监控${NC}"
                echo -e "${YELLOW}💡 说明：实时显示新的错误信息，按 Ctrl+C 退出${NC}"
                if [ -f "/var/log/nginx/error.log" ]; then
                    tail -f /var/log/nginx/error.log
                else
                    echo -e "${RED}❌ 错误日志文件不存在${NC}"
                fi
                ;;
            5)
                echo -e "\n${CYAN}🌐 站点专用日志查看${NC}"
                # 列出可用的站点日志
                local site_logs=$(find /var/log/nginx -name "*.access.log" -o -name "*.error.log" 2>/dev/null | grep -v "access.log$" | grep -v "error.log$")
                if [ -n "$site_logs" ]; then
                    echo -e "${YELLOW}可用的站点日志：${NC}"
                    local i=1
                    for log_file in $site_logs; do
                        local site_name=$(basename "$log_file" | sed 's/\.\(access\|error\)\.log$//')
                        echo -e "  ${CYAN}$i.${NC} ${WHITE}$site_name${NC} - $log_file"
                        ((i++))
                    done
                    echo
                    read -p "请选择站点编号 (回车取消): " site_log_choice
                    if [ -n "$site_log_choice" ] && [[ "$site_log_choice" =~ ^[0-9]+$ ]]; then
                        local selected_log=$(echo "$site_logs" | sed -n "${site_log_choice}p")
                        if [ -n "$selected_log" ] && [ -f "$selected_log" ]; then
                            echo -e "${YELLOW}最近30行日志内容：${NC}"
                            tail -n 30 "$selected_log"
                        else
                            echo -e "${RED}❌ 日志文件不存在${NC}"
                        fi
                    else
                        echo -e "${YELLOW}取消查看站点日志${NC}"
                    fi
                else
                    echo -e "${YELLOW}暂无站点专用日志${NC}"
                    echo -e "${CYAN}💡 说明：站点专用日志在添加站点时自动创建${NC}"
                fi
                ;;
        esac
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx性能优化
nginx_performance_optimization() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}⚡ Nginx 性能优化${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                ⚡ 性能优化${NC}"
    show_separator
    echo
    echo -e "${YELLOW}⚠️  功能正在开发中...${NC}"
    echo
    echo -e "${WHITE}🔧 计划功能：${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}工作进程优化${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}连接数优化${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}缓存配置${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Gzip压缩${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}静态文件优化${NC}"
    echo
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx备份恢复
nginx_backup_restore() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}💾 Nginx 备份恢复${NC}"
    show_separator
    
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}                💾 备份恢复管理${NC}"
    show_separator
    echo
    echo -e "${WHITE}🔧 备份操作：${NC}"
    format_list_item "1" "备份Nginx配置" "创建当前配置的备份"
    format_list_item "2" "恢复Nginx配置" "从备份中恢复配置"
    format_list_item "3" "查看备份列表" "显示所有可用备份"
    format_list_item "4" "删除备份文件" "清理不需要的备份"
    echo
    echo -e "${YELLOW}💡 备份说明：${NC}"
    echo -e "  • 备份包含: nginx.conf 和 conf.d 目录"
    echo -e "  • 备份位置: /tmp/nginx_backup_时间戳/"
    echo -e "  • 建议在修改配置前先备份"
    echo
    show_separator
    read -p "请选择操作 [1-4]: " backup_choice
    
            case $backup_choice in
            1)
                echo -e "${YELLOW}正在创建Nginx配置备份...${NC}"
                local backup_dir="/tmp/nginx_backup_$(date +%Y%m%d_%H%M%S)"
                mkdir -p "$backup_dir"
                cp -r /etc/nginx "$backup_dir/"
                echo -e "${GREEN}✅ 配置已备份到: $backup_dir${NC}"
                echo -e "${CYAN}📋 备份内容：${NC}"
                echo -e "  • nginx.conf 主配置文件"
                echo -e "  • conf.d/ 站点配置目录"
                echo -e "  • sites-available/ 子配置文件"
                ;;
            2)
                echo -e "\n${CYAN}📂 选择备份目录${NC}"
                local backup_dirs=$(ls -d /tmp/nginx_backup_* 2>/dev/null)
                if [ -n "$backup_dirs" ]; then
                    echo -e "${YELLOW}可用的备份：${NC}"
                    local i=1
                    for dir in $backup_dirs; do
                        local backup_time=$(basename "$dir" | sed 's/nginx_backup_//')
                        echo -e "  ${CYAN}$i.${NC} ${WHITE}$backup_time${NC} - $dir"
                        ((i++))
                    done
                    echo
                    read -p "请选择备份编号 (回车取消): " backup_num
                    if [ -n "$backup_num" ] && [[ "$backup_num" =~ ^[0-9]+$ ]]; then
                        local selected_backup=$(echo "$backup_dirs" | sed -n "${backup_num}p")
                        if [ -n "$selected_backup" ] && [ -d "$selected_backup" ]; then
                            echo -e "${YELLOW}正在恢复配置...${NC}"
                            cp -r "$selected_backup/nginx" /etc/
                            echo -e "${GREEN}✅ 配置已恢复${NC}"
                            echo -e "${YELLOW}💡 建议重启Nginx服务使配置生效${NC}"
                        else
                            echo -e "${RED}❌ 备份编号无效${NC}"
                        fi
                    else
                        echo -e "${YELLOW}取消恢复操作${NC}"
                    fi
                else
                    echo -e "${YELLOW}暂无可用备份${NC}"
                fi
                ;;
            3)
                echo -e "\n${CYAN}📋 备份列表${NC}"
                local backup_dirs=$(ls -d /tmp/nginx_backup_* 2>/dev/null)
                if [ -n "$backup_dirs" ]; then
                    echo -e "${WHITE}备份详情：${NC}"
                    for dir in $backup_dirs; do
                        local backup_time=$(basename "$dir" | sed 's/nginx_backup_//')
                        local backup_size=$(du -sh "$dir" 2>/dev/null | cut -f1)
                        echo -e "  ${CYAN}📁${NC} ${WHITE}$backup_time${NC}"
                        echo -e "    路径: $dir"
                        echo -e "    大小: $backup_size"
                        echo
                    done
                else
                    echo -e "${YELLOW}暂无备份文件${NC}"
                fi
                ;;
            4)
                echo -e "\n${CYAN}🗑️  删除备份文件${NC}"
                local backup_dirs=$(ls -d /tmp/nginx_backup_* 2>/dev/null)
                if [ -n "$backup_dirs" ]; then
                    echo -e "${YELLOW}可删除的备份：${NC}"
                    local i=1
                    for dir in $backup_dirs; do
                        local backup_time=$(basename "$dir" | sed 's/nginx_backup_//')
                        echo -e "  ${CYAN}$i.${NC} ${WHITE}$backup_time${NC} - $dir"
                        ((i++))
                    done
                    echo
                    read -p "请选择要删除的备份编号 (回车取消): " delete_num
                    if [ -n "$delete_num" ] && [[ "$delete_num" =~ ^[0-9]+$ ]]; then
                        local selected_backup=$(echo "$backup_dirs" | sed -n "${delete_num}p")
                        if [ -n "$selected_backup" ] && [ -d "$selected_backup" ]; then
                            read -p "确定要删除备份 $selected_backup 吗？(y/n): " confirm_delete
                            if [[ $confirm_delete =~ ^[Yy]$ ]]; then
                                rm -rf "$selected_backup"
                                echo -e "${GREEN}✅ 备份已删除${NC}"
                            else
                                echo -e "${YELLOW}取消删除操作${NC}"
                            fi
                        else
                            echo -e "${RED}❌ 备份编号无效${NC}"
                        fi
                    else
                        echo -e "${YELLOW}取消删除操作${NC}"
                    fi
                else
                    echo -e "${YELLOW}暂无备份文件可删除${NC}"
                fi
                ;;
        esac
    
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# Nginx配置检查与修复
nginx_config_check_fix() {
    echo -e "\n${CYAN}"
    show_separator
    echo -e "${WHITE}              🔧 配置检查与修复${NC}"
    show_separator
    
    echo -e "${WHITE}🔍 正在检查Nginx配置...${NC}"
    echo
    
    # 检查配置语法
    echo -e "${CYAN}📋 步骤 1/4: 检查配置语法${NC}"
    if nginx -t 2>&1 | grep -q "test is successful"; then
        echo -e "${GREEN}✅ Nginx配置语法正确${NC}"
    else
        echo -e "${RED}❌ Nginx配置语法错误${NC}"
        echo -e "${YELLOW}错误详情：${NC}"
        nginx -t
        
        echo -e "\n${CYAN}🔧 自动修复选项${NC}"
        echo -e "${YELLOW}💡 说明：${NC}"
        echo -e "  • 自动修复将尝试修复常见的配置问题"
        echo -e "  • 修复前会自动备份当前配置"
        echo -e "  • 建议在修复前手动备份重要配置"
        echo
        read -p "是否要自动修复配置问题？(y/n，回车默认y): " fix_choice
        fix_choice=${fix_choice:-y}
        
        if [[ $fix_choice =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}开始自动修复配置...${NC}"
            nginx_auto_fix_config
        else
            echo -e "${YELLOW}跳过自动修复，请手动检查配置${NC}"
        fi
        return
    fi
    
    # 检查配置文件结构
    echo -e "\n${CYAN}📋 步骤 2/4: 检查配置文件结构${NC}"
    
    # 检查nginx.conf中的include指令位置
    if grep -q "include.*conf\.d.*\.conf" /etc/nginx/nginx.conf; then
        echo -e "${GREEN}✅ conf.d目录已正确包含${NC}"
    else
        echo -e "${YELLOW}⚠️  conf.d目录未包含，正在修复...${NC}"
        nginx_fix_include_directive
    fi
    
    # 检查是否有重复的server块
    echo -e "\n${CYAN}📋 步骤 3/4: 检查重复配置${NC}"
    duplicate_servers=$(grep -r "server_name" /etc/nginx/conf.d/ 2>/dev/null | awk '{print $2}' | sort | uniq -d)
    if [ -n "$duplicate_servers" ]; then
        echo -e "${YELLOW}⚠️  发现重复的server_name:${NC}"
        echo "$duplicate_servers"
        echo -e "${CYAN}💡 建议：检查并删除重复的配置文件${NC}"
    else
        echo -e "${GREEN}✅ 未发现重复的server_name${NC}"
    fi
    
    # 检查端口冲突
    echo -e "\n${CYAN}📋 步骤 4/4: 检查端口配置${NC}"
    port_conflicts=$(grep -r "listen.*80" /etc/nginx/conf.d/ 2>/dev/null | wc -l)
    if [ $port_conflicts -gt 1 ]; then
        echo -e "${YELLOW}⚠️  发现多个配置监听80端口，这是正常的${NC}"
        echo -e "${CYAN}💡 说明：多个站点可以共享80端口，通过server_name区分${NC}"
    else
        echo -e "${GREEN}✅ 端口配置正常${NC}"
    fi
    
    # 检查错误位置的配置文件
    echo -e "\n${CYAN}🔍 额外检查：错误位置的配置文件${NC}"
    if [ -d "/etc/nginx/default.d" ] && [ "$(ls -A /etc/nginx/default.d/*.conf 2>/dev/null)" ]; then
        echo -e "${YELLOW}⚠️  发现配置文件在错误位置: /etc/nginx/default.d/${NC}"
        ls -la /etc/nginx/default.d/*.conf
        echo -e "${CYAN}💡 建议：将这些配置文件移动到正确位置${NC}"
        echo
        read -p "是否要移动这些配置文件到正确位置？(y/n，回车默认y): " move_choice
        move_choice=${move_choice:-y}
        if [[ $move_choice =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}正在移动配置文件...${NC}"
            nginx_move_config_files
        else
            echo -e "${YELLOW}跳过移动操作${NC}"
        fi
    else
        echo -e "${GREEN}✅ 未发现错误位置的配置文件${NC}"
    fi
    
    echo -e "\n${GREEN}✅ 配置检查完成${NC}"
    echo -e "${CYAN}📋 检查总结：${NC}"
    echo -e "  • 配置语法: ${GREEN}正常${NC}"
    echo -e "  • 文件结构: ${GREEN}正常${NC}"
    echo -e "  • 重复配置: ${GREEN}正常${NC}"
    echo -e "  • 端口配置: ${GREEN}正常${NC}"
    echo -e "\n${YELLOW}按回车键返回...${NC}"
    read
}

# 自动修复Nginx配置
nginx_auto_fix_config() {
    echo -e "\n${WHITE}开始自动修复配置...${NC}"
    
    # 备份当前配置
    local backup_dir="/tmp/nginx_fix_backup_$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    cp -r /etc/nginx "$backup_dir/"
    echo -e "${YELLOW}配置已备份到: $backup_dir${NC}"
    
    # 修复include指令位置
    nginx_fix_include_directive
    
    # 移动错误位置的配置文件
    if [ -d "/etc/nginx/default.d" ] && [ "$(ls -A /etc/nginx/default.d/*.conf 2>/dev/null)" ]; then
        echo -e "${WHITE}移动错误位置的配置文件...${NC}"
        nginx_move_config_files
    fi
    
    # 检查并修复配置文件
    for conf_file in /etc/nginx/conf.d/*.conf; do
        if [ -f "$conf_file" ]; then
            echo -e "${WHITE}检查配置文件: $conf_file${NC}"
            
            # 检查文件是否在http块外有server指令
            if grep -q "^server {" "$conf_file"; then
                echo -e "${GREEN}✅ $conf_file 结构正确${NC}"
            else
                echo -e "${YELLOW}⚠️  修复 $conf_file${NC}"
                nginx_fix_server_block "$conf_file"
            fi
        fi
    done
    
    # 重新测试配置
    echo -e "\n${WHITE}重新测试配置...${NC}"
    if nginx -t 2>&1 | grep -q "test is successful"; then
        echo -e "${GREEN}✅ 配置修复成功！${NC}"
        echo -e "${YELLOW}是否要重载Nginx配置？(y/n，默认y): " reload_choice
        reload_choice=${reload_choice:-y}
        if [[ $reload_choice =~ ^[Yy]$ ]]; then
            reload_nginx_config "配置修复"
        fi
    else
        echo -e "${RED}❌ 配置修复失败，请手动检查${NC}"
        nginx -t
    fi
}

# 修复include指令位置
nginx_fix_include_directive() {
    echo -e "${WHITE}修复include指令位置...${NC}"
    
    # 移除错误的include指令
    sed -i '/include.*conf\.d.*\.conf/d' /etc/nginx/nginx.conf
    
    # 在http块末尾添加正确的include指令
    if grep -q "http {" /etc/nginx/nginx.conf; then
        # 查找http块的结束位置并添加include
        sed -i '/^    }$/i\    include /etc/nginx/conf.d/*.conf;' /etc/nginx/nginx.conf
        echo -e "${GREEN}✅ include指令已修复${NC}"
    else
        echo -e "${RED}❌ 未找到http块，请手动检查nginx.conf${NC}"
    fi
}

# 修复server块结构
nginx_fix_server_block() {
    local conf_file="$1"
    local temp_file="/tmp/nginx_fix_$(basename "$conf_file")"
    
    # 创建临时文件
    cat > "$temp_file" << 'EOF'
# 修复后的配置文件
server {
EOF
    
    # 提取server块内容（去掉开头的server {）
    sed '1d' "$conf_file" >> "$temp_file"
    
    # 替换原文件
    mv "$temp_file" "$conf_file"
    echo -e "${GREEN}✅ $conf_file 已修复${NC}"
}

# 移动配置文件到正确位置
nginx_move_config_files() {
    echo -e "${WHITE}移动配置文件到正确位置...${NC}"
    
    # 确保目标目录存在
    mkdir -p /etc/nginx/conf.d
    
    # 移动default.d中的配置文件到conf.d
    for conf_file in /etc/nginx/default.d/*.conf; do
        if [ -f "$conf_file" ]; then
            local filename=$(basename "$conf_file")
            echo -e "${WHITE}移动: $conf_file -> /etc/nginx/conf.d/$filename${NC}"
            mv "$conf_file" "/etc/nginx/conf.d/$filename"
        fi
    done
    
    # 检查是否还有其他错误位置的配置文件
    for dir in /etc/nginx/*.d; do
        if [ -d "$dir" ] && [ "$dir" != "/etc/nginx/conf.d" ] && [ "$dir" != "/etc/nginx/sites-available" ] && [ "$dir" != "/etc/nginx/sites-enabled" ]; then
            if [ "$(ls -A "$dir"/*.conf 2>/dev/null)" ]; then
                echo -e "${YELLOW}⚠️  发现其他位置的配置文件: $dir${NC}"
                ls -la "$dir"/*.conf
                echo -e "${WHITE}是否要移动这些配置文件？(y/n，默认y): " move_other_choice
                move_other_choice=${move_other_choice:-y}
                if [[ $move_other_choice =~ ^[Yy]$ ]]; then
                    for conf_file in "$dir"/*.conf; do
                        if [ -f "$conf_file" ]; then
                            local filename=$(basename "$conf_file")
                            echo -e "${WHITE}移动: $conf_file -> /etc/nginx/conf.d/$filename${NC}"
                            mv "$conf_file" "/etc/nginx/conf.d/$filename"
                        fi
                    done
                fi
            fi
        fi
    done
    
    echo -e "${GREEN}✅ 配置文件移动完成${NC}"
}

# 安装MySQL 5.7
install_mysql() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装MySQL 5.7${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "MySQL" "mysql" ""; then
        echo -e "${YELLOW}⚠️  MySQL 已安装${NC}"
        read -p "是否要卸载现有MySQL？(y/n，默认n): " uninstall_mysql
        if [[ $uninstall_mysql =~ ^[Yy]$ ]]; then
            uninstall_component "MySQL" "yum remove -y mysql-community-server mysql-community-client"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过MySQL安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}📋 步骤 1/6: 清理旧版本MySQL...${NC}"
    # 清理旧版本MySQL
    yum remove -y mysql mysql-server mysql-libs mysql-common
    rm -rf /var/lib/mysql
    rm -rf /etc/my.cnf
    rm -rf /etc/mysql
    
    echo -e "${YELLOW}📋 步骤 2/6: 下载MySQL 5.7仓库...${NC}"
    wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
    
    echo -e "${YELLOW}📋 步骤 3/6: 安装MySQL仓库...${NC}"
    rpm -ivh mysql57-community-release-el7-11.noarch.rpm
    
    echo -e "${YELLOW}📋 步骤 4/6: 导入MySQL GPG密钥...${NC}"
    # 导入MySQL GPG密钥
    rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
    
    echo -e "${YELLOW}📋 步骤 5/6: 安装MySQL 5.7...${NC}"
    # 使用--nogpgcheck跳过GPG验证，或者使用--import导入密钥
    yum install -y mysql-community-server --nogpgcheck
    
    echo -e "${YELLOW}📋 步骤 6/6: 配置MySQL端口...${NC}"
    # 交互式配置MySQL端口
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔌 MySQL端口配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}端口说明：${NC}"
    echo -e "  ${CYAN}默认端口${NC}: 3306 (MySQL标准端口)"
    echo -e "  ${CYAN}自定义端口${NC}: 可自定义任意可用端口"
    echo
    read -p "请输入MySQL端口 (回车默认3306): " mysql_port
    mysql_port=${mysql_port:-3306}
    
    # 验证端口是否有效
    if [[ ! "$mysql_port" =~ ^[0-9]+$ ]] || [ "$mysql_port" -lt 1 ] || [ "$mysql_port" -gt 65535 ]; then
        echo -e "${RED}❌ 端口号无效，使用默认端口3306${NC}"
        mysql_port=3306
    fi
    
    echo -e "${GREEN}✅ MySQL端口设置为: ${CYAN}$mysql_port${NC}"
    
    # 交互式配置MySQL字符集
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔤 MySQL字符集配置(character-set-server)${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}字符集说明：${NC}"
    echo -e "  ${CYAN}utf8mb4${NC}: 支持完整的UTF-8编码，包括emoji表情（推荐）"
    echo -e "  ${CYAN}utf8${NC}: 标准UTF-8编码"
    echo -e "  ${CYAN}gbk${NC}: 中文GBK编码"
    echo
    read -p "请输入MySQL字符集 (回车默认utf8mb4): " mysql_charset
    mysql_charset=${mysql_charset:-utf8mb4}
    
    # 验证字符集是否有效
    valid_charsets=("utf8mb4" "utf8" "latin1" "gbk" "big5" "ascii" "binary" "cp850" "cp866" "dec8" "eucjpms" "euckr" "gb2312" "gb18030" "hebrew" "hp8" "keybcs2" "koi8r" "koi8u" "latin2" "latin5" "latin7" "macce" "macroman" "sjis" "swe7" "tis620" "ucs2" "ujis")
    charset_valid=false
    for charset in "${valid_charsets[@]}"; do
        if [ "$mysql_charset" = "$charset" ]; then
            charset_valid=true
            break
        fi
    done
    
    if [ "$charset_valid" = false ]; then
        echo -e "${RED}❌ 字符集 '$mysql_charset' 无效，使用默认字符集 utf8mb4${NC}"
        echo -e "${YELLOW}支持的字符集: ${CYAN}${valid_charsets[*]}${NC}"
        mysql_charset=utf8mb4
    else
        echo -e "${GREEN}✅ MySQL字符集设置为: ${CYAN}$mysql_charset${NC}"
    fi
    
    # 修改MySQL配置文件中的端口和字符集
    if [ -f /etc/my.cnf ]; then
        # 检查是否已有port配置
        if grep -q "^port" /etc/my.cnf; then
            sed -i "s/^port.*/port = $mysql_port/" /etc/my.cnf
        else
            # 在[mysqld]段添加port配置
            sed -i "/^\[mysqld\]/a port = $mysql_port" /etc/my.cnf
        fi
        
        # 检查是否已有character-set-server配置
        if grep -q "^character-set-server" /etc/my.cnf; then
            sed -i "s/^character-set-server.*/character-set-server = $mysql_charset/" /etc/my.cnf
        else
            # 在[mysqld]段添加character-set-server配置
            sed -i "/^\[mysqld\]/a character-set-server = $mysql_charset" /etc/my.cnf
        fi
    else
        # 创建MySQL配置文件
        cat > /etc/my.cnf << EOF
[mysqld]
port = $mysql_port
character-set-server = $mysql_charset
datadir = /var/lib/mysql
socket = /var/lib/mysql/mysql.sock
user = mysql
symbolic-links = 0
log-error = /var/log/mysqld.log
pid-file = /var/run/mysqld/mysqld.pid

[mysql]
socket = /var/lib/mysql/mysql.sock
EOF
    fi
    
    echo -e "${YELLOW}📋 步骤 7/7: 启动MySQL服务...${NC}"
    # 初始化MySQL数据目录
    mysqld --initialize-insecure --user=mysql
    
    # 启动MySQL服务
    systemctl start mysqld
    systemctl enable mysqld
    
    # 验证MySQL是否启动成功
    sleep 3
    if systemctl is-active --quiet mysqld; then
        echo -e "${GREEN}✅ MySQL 5.7 安装完成并启动成功！${NC}"
        echo -e "${CYAN}MySQL进程信息：${NC}"
        ps -ef | grep mysqld | grep -v grep
        echo
        
        # 交互式设置MySQL root密码
        echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}🔐 MySQL Root密码配置${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${YELLOW}密码说明：${NC}"
        echo -e "  ${CYAN}设置密码${NC}: 提高安全性，连接时需要密码"
        echo -e "  ${CYAN}不设置密码${NC}: 方便开发，但安全性较低"
        echo
        read -p "是否要设置MySQL root密码？(y/n，默认y): " set_mysql_password
        if [[ $set_mysql_password =~ ^[Nn]$ ]]; then
            echo -e "${YELLOW}跳过密码设置，保持空密码${NC}"
            mysql_password=""
        else
            while true; do
                read -s -p "请输入MySQL root密码: " mysql_password
                echo
                # 如果用户直接按回车，设置默认密码为123456
                if [ -z "$mysql_password" ]; then
                    mysql_password="123456"
                    echo -e "${GREEN}✅ 使用默认密码: 123456${NC}"
                    break
                else
                    read -s -p "请再次输入密码确认: " mysql_password_confirm
                    echo
                    if [ "$mysql_password" = "$mysql_password_confirm" ]; then
                        echo -e "${GREEN}密码设置成功！${NC}"
                        break
                    else
                        echo -e "${RED}两次输入的密码不一致，请重新输入${NC}"
                    fi
                fi
            done
            
            # 设置MySQL root密码
            echo -e "${YELLOW}正在设置MySQL root密码...${NC}"
            mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$mysql_password';"
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}✅ MySQL root密码设置成功！${NC}"
            else
                echo -e "${RED}❌ MySQL root密码设置失败${NC}"
                mysql_password=""
            fi
        fi
        
        # 交互式配置远程连接
        echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}🌐 MySQL远程连接配置${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${YELLOW}远程连接说明：${NC}"
        echo -e "  ${CYAN}允许远程连接${NC}: 可以从其他机器连接MySQL"
        echo -e "  ${CYAN}仅本地连接${NC}: 只能从本机连接MySQL，更安全"
        echo
        read -p "是否允许MySQL远程连接？(y/n，默认y): " allow_remote_mysql
        if [[ $allow_remote_mysql =~ ^[Nn]$ ]]; then
            echo -e "${YELLOW}保持仅本地连接模式${NC}"
        else
            echo -e "${YELLOW}正在配置远程连接...${NC}"
            if [ -n "$mysql_password" ]; then
                mysql -u root -p"$mysql_password" -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '$mysql_password';"
            else
                mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';"
            fi
            mysql -u root -e "FLUSH PRIVILEGES;"
            echo -e "${GREEN}✅ MySQL远程连接配置完成！${NC}"
        fi
        
        echo
        echo -e "${CYAN}连接信息：${NC}"
        echo -e "  端口: ${CYAN}$mysql_port${NC}"
        if [ -n "$mysql_password" ]; then
            echo -e "  密码: ${CYAN}已设置${NC}"
            echo -e "  连接命令: ${CYAN}mysql -u root -p -P $mysql_port${NC}"
        else
            echo -e "  密码: ${CYAN}无（空密码）${NC}"
            echo -e "  连接命令: ${CYAN}mysql -u root -P $mysql_port${NC}"
        fi
        echo -e "  服务管理: ${CYAN}systemctl start/stop/restart mysqld${NC}"
        echo
        echo -e "${CYAN}使用提示：${NC}"
        if [ -n "$mysql_password" ]; then
            echo -e "  • 连接MySQL: mysql -u root -p -P $mysql_port"
        else
            echo -e "  • 连接MySQL: mysql -u root -P $mysql_port"
        fi
        if [[ $allow_remote_mysql =~ ^[Nn]$ ]]; then
            echo -e "  • 仅支持本地连接，如需远程连接请手动配置"
        else
            echo -e "  • 远程连接已启用，可从其他机器连接"
        fi
    else
        echo -e "${RED}❌ MySQL启动失败${NC}"
        echo -e "${YELLOW}请检查日志: journalctl -u mysqld${NC}"
        echo -e "${YELLOW}手动启动: systemctl start mysqld${NC}"
    fi
}

# 安装Redis
install_redis() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Redis${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Redis" "redis-server" "/www/server/redis"; then
        echo -e "${YELLOW}⚠️  Redis 已安装${NC}"
        read -p "是否要卸载现有Redis？(y/n，默认n): " uninstall_redis
        if [[ $uninstall_redis =~ ^[Yy]$ ]]; then
            uninstall_component "Redis" "rm -rf /www/server/redis"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过Redis安装${NC}"
            return
        fi
    fi
    
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}正在下载Redis 3.2.9...${NC}"
    wget https://download.redis.io/releases/redis-3.2.9.tar.gz
    
    echo -e "${YELLOW}正在解压Redis...${NC}"
    tar -zxvf redis-3.2.9.tar.gz
    rm -f redis-3.2.9.tar.gz
    mv redis-3.2.9 redis
    
    echo -e "${YELLOW}正在编译和安装Redis...${NC}"
    cd /www/server/redis
    make
    cd src
    make install
    
    echo -e "${YELLOW}配置Redis...${NC}"
    cd /www/server/redis
    
    # 保护模式配置
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔒 Redis保护模式配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}保护模式说明：${NC}"
    echo -e "  ${CYAN}启动保护模式${NC}: 只允许本地连接，更安全"
    echo -e "  ${CYAN}不启动保护模式${NC}: 允许远程连接，方便开发"
    echo
    read -p "Redis需要启动保护模式? 1.启动 2.不启动(回车默认不启动): " Redis2
    if [ "$Redis2" == "1" ]; then
        echo -e "${PURPLE}你选择了Redis启动保护模式.....${NC}"
        sed -i "s/protected-mode no/protected-mode yes/" redis.conf
    else
        sed -i "s/protected-mode yes/protected-mode no/" redis.conf
        echo -e "${PURPLE}你选择了Redis不启动保护模式......${NC}"
    fi
    
    # 修改绑定地址
    sed -i "s/127.0.0.1/0.0.0.0/" redis.conf
    
    # 启动模式配置
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🚀 Redis启动模式配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}启动模式说明：${NC}"
    echo -e "  ${CYAN}前端启动${NC}: 在当前终端运行，关闭终端会停止Redis"
    echo -e "  ${CYAN}后端启动${NC}: 在后台运行，关闭终端不会影响Redis"
    echo
    read -p "Redis需要后端启动模式? 1.前端启动 2.后端启动(回车默认后端启动): " Redis3
    if [ "$Redis3" == "1" ]; then
        echo -e "${PURPLE}你选择了Redis前端启动模式......${NC}"
        sed -i "s/daemonize yes/daemonize no/" redis.conf
    else
        sed -i "s/daemonize no/daemonize yes/" redis.conf
        echo -e "${PURPLE}你选择了Redis后端启动模式......${NC}"
    fi
    
    # 端口配置
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔌 Redis端口配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}端口说明：${NC}"
    echo -e "  ${CYAN}默认端口${NC}: 6379 (Redis标准端口)"
    echo -e "  ${CYAN}自定义端口${NC}: 可自定义任意可用端口"
    echo
    read -p "Redis需要修改端口? 1.默认端口(回车使用默认端口) 2.自定义端口: " PortType
    if [ "$PortType" == "2" ]; then
        read -p "你选择Redis自定义端口模式，请输入端口: " RedisPort
        echo -e "${PURPLE}正在执行修改Redis端口.....${NC}"
        sed -i "s/6379/$RedisPort/" /www/server/redis/redis.conf
        iptables -I INPUT -ptcp --dport $RedisPort -j ACCEPT
        echo -e "${PURPLE}你选择了Redis自定义端口为$RedisPort,请牢记。${NC}"
    else
        iptables -I INPUT -ptcp --dport 6379 -j ACCEPT
        echo -e "${PURPLE}你选择了Redis初始化使用默认端口6379,请牢记。${NC}"
    fi
    
    # 密码配置
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔐 Redis密码配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}密码说明：${NC}"
    echo -e "  ${CYAN}添加密码${NC}: 提高安全性，连接时需要密码"
    echo -e "  ${CYAN}不添加密码${NC}: 方便开发，但安全性较低"
    echo
    read -p "Redis需要添加密码? 1.添加密码 2.不添加(回车默认没密码): " PassWordType
    if [ "$PassWordType" == "1" ]; then
        read -p "请你输入要设置Redis的密码: " RedisPassWord
        echo -e "${PURPLE}正在添加Redis密码.....${NC}"
        sed -i "s/# requirepass foobared/requirepass $RedisPassWord/" redis.conf
        echo -e "${PURPLE}你添加了Redis密码，Redis密码为$RedisPassWord。${NC}"
    else
        echo -e "${PURPLE}你选择了Redis默认没密码......${NC}"
    fi
    
    # 启动Redis
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🚀 启动Redis服务${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    cd /www/server/redis/src
    ./redis-server ../redis.conf
    
    # 验证安装
    sleep 2
    if pgrep -x "redis-server" > /dev/null; then
        echo -e "${GREEN}✅ Redis 安装完成并启动成功！${NC}"
        echo -e "${CYAN}Redis进程信息：${NC}"
        ps -ef | grep redis-server | grep -v grep
        echo
        echo -e "${CYAN}连接信息：${NC}"
        if [ "$PortType" == "2" ]; then
            echo -e "  端口: ${CYAN}$RedisPort${NC}"
        else
            echo -e "  端口: ${CYAN}6379${NC}"
        fi
        if [ "$PassWordType" == "1" ]; then
            echo -e "  密码: ${CYAN}$RedisPassWord${NC}"
        else
            echo -e "  密码: ${CYAN}无${NC}"
        fi
        echo -e "  连接命令: ${CYAN}redis-cli -h 127.0.0.1${NC}"
    else
        echo -e "${RED}❌ Redis启动失败${NC}"
    fi
}

# 安装SVN
install_svn() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装SVN${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "SVN" "svn" ""; then
        echo -e "${YELLOW}⚠️  SVN 已安装${NC}"
        read -p "是否要卸载现有SVN？(y/n，默认n): " uninstall_svn
        if [[ $uninstall_svn =~ ^[Yy]$ ]]; then
            uninstall_component "SVN" "yum remove -y subversion && rm -rf /www/server/svnFile"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过SVN安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}📋 步骤 1/6: 安装SVN软件包...${NC}"
    yum install -y subversion
    echo -e "${GREEN}✅ SVN软件包安装完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 2/6: 创建SVN仓库目录...${NC}"
    mkdir -p /www/server/svnFile
    echo -e "${GREEN}✅ 目录创建完成: /www/server/svnFile${NC}"
    
    echo -e "${YELLOW}📋 步骤 3/6: 初始化SVN仓库...${NC}"
    svnadmin create /www/server/svnFile
    echo -e "${GREEN}✅ SVN仓库初始化完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 4/6: 配置SVN用户账户...${NC}"
    # 交互式配置SVN用户
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}👥 SVN用户配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}用户配置说明：${NC}"
    echo -e "  ${CYAN}默认用户${NC}: admin (密码: 123456)"
    echo -e "  ${CYAN}测试用户${NC}: test (密码: 123456)"
    echo -e "  ${CYAN}自定义用户${NC}: 可以添加更多用户"
    echo
    read -p "是否要添加自定义用户？(y/n，默认n): " add_custom_svn_user
    if [[ $add_custom_svn_user =~ ^[Yy]$ ]]; then
        while true; do
            read -p "请输入用户名 (输入'q'退出): " svn_username
            if [ "$svn_username" = "q" ]; then
                break
            fi
            if [ -n "$svn_username" ]; then
                read -s -p "请输入密码: " svn_password
                echo
                echo -e "$svn_username = $svn_password" >> /www/server/svnFile/conf/passwd
                echo -e "${GREEN}✅ 用户 $svn_username 添加成功${NC}"
            fi
        done
    fi
    
    # 添加默认用户
    echo -e '\nadmin = 123456\ntest = 123456\n' >> /www/server/svnFile/conf/passwd
    echo -e "${GREEN}✅ 默认用户配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 5/6: 配置SVN权限和访问控制...${NC}"
    # 配置SVN服务配置文件
    echo -e "${WHITE}配置SVN服务参数...${NC}"
    sed -i 's/# anon-access = read/anon-access = read/' /www/server/svnFile/conf/svnserve.conf
    sed -i 's/# auth-access = write/auth-access = write/' /www/server/svnFile/conf/svnserve.conf
    sed -i 's/# password-db = passwd/password-db = passwd/' /www/server/svnFile/conf/svnserve.conf
    sed -i 's/# authz-db = authz/authz-db = authz/' /www/server/svnFile/conf/svnserve.conf
    echo -e "${GREEN}✅ SVN服务配置完成${NC}"
    
    # 配置权限文件
    echo -e "${WHITE}配置用户权限...${NC}"
    cat > /www/server/svnFile/conf/authz << EOF
[groups]
admin = admin
developers = test

[/]
admin = rw
developers = rw
* = r
EOF
    echo -e "${GREEN}✅ 权限配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 6/6: 启动SVN服务...${NC}"
    # 启动SVN服务
    svnserve -d -r /www/server/svnFile/
    
    # 验证SVN服务是否启动成功
    sleep 2
    if pgrep -x "svnserve" > /dev/null; then
        echo -e "${GREEN}✅ SVN 安装完成并启动成功！${NC}"
        echo -e "${CYAN}SVN进程信息：${NC}"
        ps -ef | grep svnserve | grep -v grep
        echo
        echo -e "${CYAN}连接信息：${NC}"
        echo -e "  仓库端口: ${CYAN}3690${NC}"
        echo -e "  仓库地址: ${CYAN}svn://$(curl -s ipinfo.io/ip):3690/svnFile${NC}"
        echo -e "  默认用户: ${CYAN}admin / 123456${NC}"
        echo -e "  测试用户: ${CYAN}test / 123456${NC}"
        echo
        echo -e "${CYAN}使用提示：${NC}"
        echo -e "  • 检出仓库: svn checkout svn://$(curl -s ipinfo.io/ip):3690/svnFile"
        echo -e "  • 导入项目: svn import /path/to/project svn://$(curl -s ipinfo.io/ip):3690/svnFile/project"
        echo -e "  • 查看日志: svn log svn://$(curl -s ipinfo.io/ip):3690/svnFile"
        echo -e "  • 停止服务: pkill svnserve"
    else
        echo -e "${RED}❌ SVN启动失败${NC}"
        echo -e "${YELLOW}请检查配置: /www/server/svnFile/conf/svnserve.conf${NC}"
    fi
}

# 安装FTP
install_ftp() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装FTP${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "FTP" "vsftpd" ""; then
        echo -e "${YELLOW}⚠️  FTP 已安装${NC}"
        read -p "是否要卸载现有FTP？(y/n，默认n): " uninstall_ftp
        if [[ $uninstall_ftp =~ ^[Yy]$ ]]; then
            uninstall_component "FTP" "yum remove -y vsftpd"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过FTP安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}📋 步骤 1/6: 安装vsftpd软件包...${NC}"
    yum install -y vsftpd
    echo -e "${GREEN}✅ vsftpd软件包安装完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 2/6: 配置FTP用户和目录...${NC}"
    # 创建FTP用户目录
    mkdir -p /var/ftp/pub
    chown ftp:ftp /var/ftp/pub
    chmod 755 /var/ftp/pub
    echo -e "${GREEN}✅ FTP目录配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 3/6: 配置FTP安全设置...${NC}"
    # 交互式配置FTP安全设置
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔒 FTP安全配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}安全配置说明：${NC}"
    echo -e "  ${CYAN}禁用匿名访问${NC}: 提高安全性，需要用户账户"
    echo -e "  ${CYAN}允许匿名访问${NC}: 方便测试，但是安全性较低"
    echo
    read -p "是否禁用匿名访问？(y/n，默认y): " disable_anonymous
    if [[ $disable_anonymous =~ ^[Nn]$ ]]; then
        echo -e "${YELLOW}保持匿名访问模式${NC}"
        # 保持匿名访问，但限制权限
        sed -i 's/anonymous_enable=YES/anonymous_enable=YES/' /etc/vsftpd/vsftpd.conf
        sed -i 's/anonymous_enable=NO/anonymous_enable=YES/' /etc/vsftpd/vsftpd.conf
    else
        echo -e "${YELLOW}禁用匿名访问${NC}"
        sed -i 's/anonymous_enable=YES/anonymous_enable=NO/' /etc/vsftpd/vsftpd.conf
    fi
    echo -e "${GREEN}✅ FTP安全配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 4/6: 配置FTP用户账户...${NC}"
    # 交互式配置FTP用户
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}👥 FTP用户配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}用户配置说明：${NC}"
    echo -e "  ${CYAN}系统用户模式${NC}: 使用现有的系统用户账户登录FTP"
    echo -e "    • 优点: 无需额外创建用户，直接使用现有账户"
    echo -e "    • 缺点: 系统用户权限较大，安全性相对较低"
    echo -e "    • 适用: 个人使用或内部网络环境"
    echo
    echo -e "  ${CYAN}专用FTP用户模式${NC}: 创建专门用于FTP访问的用户账户"
    echo -e "    • 优点: 权限隔离，安全性高，便于管理"
    echo -e "    • 缺点: 需要额外创建用户账户"
    echo -e "    • 适用: 生产环境、多用户共享、安全要求高的场景"
    echo
    echo -e "${YELLOW}推荐选择：${NC}"
    echo -e "  • 个人使用/测试环境: 选择 ${CYAN}系统用户模式${NC}"
    echo -e "  • 生产环境/多用户: 选择 ${CYAN}专用FTP用户模式${NC}"
    echo
    read -p "请选择用户模式 (1.系统用户 2.专用FTP用户，默认2): " user_mode_choice
    if [[ $user_mode_choice == "1" ]]; then
        create_ftp_user="n"
        echo -e "${YELLOW}已选择系统用户模式${NC}"
        echo -e "${CYAN}提示：您可以使用现有的系统用户（如root、普通用户等）登录FTP${NC}"
    else
        create_ftp_user="y"
        echo -e "${YELLOW}已选择专用FTP用户模式${NC}"
    fi
    if [[ $create_ftp_user =~ ^[Yy]$ ]]; then
        echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}🔧 创建专用FTP用户${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${YELLOW}用户创建说明：${NC}"
        echo -e "  • 用户名: 建议使用英文、数字和下划线，长度3-20字符"
        echo -e "  • 密码: 建议包含大小写字母、数字和特殊字符"
        echo -e "  • 用户目录: 自动创建在 /home/[用户名] 目录"
        echo -e "  • 权限: 用户只能通过FTP访问，不能SSH登录"
        echo -e "  • 可以创建多个用户，输入'q'退出创建"
        echo
        while true; do
            read -p "请输入FTP用户名 (输入'q'退出): " ftp_username
            if [ "$ftp_username" = "q" ]; then
                echo -e "${YELLOW}用户创建完成${NC}"
                break
            fi
            if [ -n "$ftp_username" ]; then
                # 验证用户名格式
                if [[ ! "$ftp_username" =~ ^[a-zA-Z0-9_]{3,20}$ ]]; then
                    echo -e "${RED}❌ 用户名格式无效，请使用3-20位英文、数字或下划线${NC}"
                    continue
                fi
                
                # 检查用户是否已存在
                if id "$ftp_username" &>/dev/null; then
                    echo -e "${RED}❌ 用户 $ftp_username 已存在，请使用其他用户名${NC}"
                    continue
                fi
                
                read -s -p "请输入密码: " ftp_password
                echo
                if [ -z "$ftp_password" ]; then
                    echo -e "${RED}❌ 密码不能为空${NC}"
                    continue
                fi
                
                read -s -p "请再次输入密码确认: " ftp_password_confirm
                echo
                if [ "$ftp_password" = "$ftp_password_confirm" ]; then
                    # 创建FTP用户
                    useradd -m -d /home/$ftp_username -s /sbin/nologin $ftp_username
                    echo "$ftp_username:$ftp_password" | chpasswd
                    echo -e "${GREEN}✅ FTP用户 $ftp_username 创建成功${NC}"
                    echo -e "${CYAN}  用户目录: /home/$ftp_username${NC}"
                    echo -e "${CYAN}  登录方式: FTP客户端${NC}"
                    echo -e "${CYAN}  权限限制: 仅FTP访问，无SSH权限${NC}"
                else
                    echo -e "${RED}❌ 两次输入的密码不一致，请重新输入${NC}"
                fi
            else
                echo -e "${RED}❌ 用户名不能为空${NC}"
            fi
        done
    fi
    echo -e "${GREEN}✅ FTP用户配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 5/6: 配置FTP端口和防火墙...${NC}"
    # 交互式配置FTP端口
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔌 FTP端口配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}端口说明：${NC}"
    echo -e "  ${CYAN}默认端口${NC}: 21 (FTP标准端口)"
    echo -e "  ${CYAN}自定义端口${NC}: 可自定义任意可用端口"
    echo
    read -p "请输入FTP端口 (回车默认21): " ftp_port
    ftp_port=${ftp_port:-21}
    
    # 验证端口是否有效
    if [[ ! "$ftp_port" =~ ^[0-9]+$ ]] || [ "$ftp_port" -lt 1 ] || [ "$ftp_port" -gt 65535 ]; then
        echo -e "${RED}❌ 端口号无效，使用默认端口21${NC}"
        ftp_port=21
    fi
    
    # 配置FTP端口
    if [ "$ftp_port" != "21" ]; then
        echo "listen_port=$ftp_port" >> /etc/vsftpd/vsftpd.conf
        echo -e "${GREEN}✅ FTP端口设置为: ${CYAN}$ftp_port${NC}"
    else
        echo -e "${GREEN}✅ 使用默认FTP端口: ${CYAN}21${NC}"
    fi
    
    # 配置防火墙
    firewall-cmd --permanent --add-port=$ftp_port/tcp
    firewall-cmd --reload
    echo -e "${GREEN}✅ 防火墙配置完成${NC}"
    
    echo -e "${YELLOW}📋 步骤 6/6: 启动FTP服务...${NC}"
    # 启动FTP服务
    systemctl start vsftpd
    systemctl enable vsftpd
    
    # 验证FTP服务是否启动成功
    sleep 2
    if systemctl is-active --quiet vsftpd; then
        echo -e "${GREEN}✅ FTP 安装完成并启动成功！${NC}"
        echo -e "${CYAN}FTP进程信息：${NC}"
        ps -ef | grep vsftpd | grep -v grep
        echo
        echo -e "${CYAN}连接信息：${NC}"
        echo -e "  端口: ${CYAN}$ftp_port${NC}"
        echo -e "  服务状态: ${CYAN}运行中${NC}"
        echo -e "  服务管理: ${CYAN}systemctl start/stop/restart vsftpd${NC}"
        echo
        echo -e "${CYAN}使用提示：${NC}"
        echo -e "  • FTP客户端连接: ftp://$(curl -s ipinfo.io/ip):$ftp_port"
        echo -e "  • 匿名访问目录: /var/ftp/pub"
        if [[ $create_ftp_user =~ ^[Yy]$ ]]; then
            echo -e "  • 用户访问目录: /home/[用户名]"
        fi
        echo -e "  • 查看FTP日志: tail -f /var/log/vsftpd.log"
        echo -e "  • 配置文件: /etc/vsftpd/vsftpd.conf"
    else
        echo -e "${RED}❌ FTP启动失败${NC}"
        echo -e "${YELLOW}请检查配置: /etc/vsftpd/vsftpd.conf${NC}"
        echo -e "${YELLOW}查看日志: journalctl -u vsftpd${NC}"
    fi
}

# 安装ZooKeeper
install_zookeeper() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装ZooKeeper${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "ZooKeeper" "" "/www/server/zookeeper"; then
        echo -e "${YELLOW}⚠️  ZooKeeper 已安装${NC}"
        read -p "是否要卸载现有ZooKeeper？(y/n，默认n): " uninstall_zookeeper
        if [[ $uninstall_zookeeper =~ ^[Yy]$ ]]; then
            uninstall_component "ZooKeeper" "rm -rf /www/server/zookeeper"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过ZooKeeper安装${NC}"
            return
        fi
    fi
    
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}下载ZooKeeper...${NC}"
    wget https://archive.apache.org/dist/zookeeper/zookeeper-3.7.1/apache-zookeeper-3.7.1-bin.tar.gz
    
    echo -e "${YELLOW}解压ZooKeeper...${NC}"
    tar -xzf apache-zookeeper-3.7.1-bin.tar.gz
    mv apache-zookeeper-3.7.1-bin /www/server/zookeeper
    
    echo -e "${YELLOW}配置ZooKeeper...${NC}"
    cp /www/server/zookeeper/conf/zoo_sample.cfg /www/server/zookeeper/conf/zoo.cfg
    
    echo -e "${YELLOW}创建数据目录...${NC}"
    mkdir -p /www/server/zookeeper/data
    
    echo -e "${GREEN}✅ ZooKeeper 安装完成！${NC}"
}

# 安装RabbitMQ
install_rabbitmq() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装RabbitMQ${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "RabbitMQ" "rabbitmq-server" ""; then
        echo -e "${YELLOW}⚠️  RabbitMQ 已安装${NC}"
        read -p "是否要卸载现有RabbitMQ？(y/n，默认n): " uninstall_rabbitmq
        if [[ $uninstall_rabbitmq =~ ^[Yy]$ ]]; then
            uninstall_component "RabbitMQ" "yum remove -y rabbitmq-server erlang"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过RabbitMQ安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}安装Erlang...${NC}"
    yum install -y epel-release
    yum install -y erlang
    
    echo -e "${YELLOW}安装RabbitMQ...${NC}"
    yum install -y rabbitmq-server
    
    echo -e "${YELLOW}启动RabbitMQ服务...${NC}"
    systemctl start rabbitmq-server
    systemctl enable rabbitmq-server
    
    echo -e "${YELLOW}启用管理插件...${NC}"
    rabbitmq-plugins enable rabbitmq_management
    
    echo -e "${GREEN}✅ RabbitMQ 安装完成！${NC}"
    echo -e "${CYAN}管理界面: http://$(curl -s ipinfo.io/ip):15672${NC}"
}

# 安装Kafka
install_kafka() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Kafka${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Kafka" "" "/www/server/kafka"; then
        echo -e "${YELLOW}⚠️  Kafka 已安装${NC}"
        read -p "是否要卸载现有Kafka？(y/n，默认n): " uninstall_kafka
        if [[ $uninstall_kafka =~ ^[Yy]$ ]]; then
            uninstall_component "Kafka" "rm -rf /www/server/kafka"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过Kafka安装${NC}"
            return
        fi
    fi
    
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}下载Kafka...${NC}"
    wget https://archive.apache.org/dist/kafka/2.5.0/kafka_2.12-2.5.0.tgz
    
    echo -e "${YELLOW}解压Kafka...${NC}"
    tar -xzf kafka_2.12-2.5.0.tgz
    mv kafka_2.12-2.5.0 /www/server/kafka
    
    echo -e "${YELLOW}创建日志目录...${NC}"
    mkdir -p /www/server/kafka/logs
    
    echo -e "${GREEN}✅ Kafka 安装完成！${NC}"
}

# 安装ELK Stack
install_elk() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装ELK Stack${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "ELK Stack" "" "/www/server/elasticsearch"; then
        echo -e "${YELLOW}⚠️  ELK Stack 已安装${NC}"
        read -p "是否要卸载现有ELK Stack？(y/n，默认n): " uninstall_elk
        if [[ $uninstall_elk =~ ^[Yy]$ ]]; then
            uninstall_component "ELK Stack" "rm -rf /www/server/elasticsearch /www/server/logstash /www/server/kibana"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过ELK Stack安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}安装Java依赖...${NC}"
    yum install -y java-1.8.0-openjdk
    
    echo -e "${YELLOW}下载Elasticsearch...${NC}"
    cd $INSTALL_DIR
    wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.10.0-linux-x86_64.tar.gz
    tar -xzf elasticsearch-7.10.0-linux-x86_64.tar.gz
    mv elasticsearch-7.10.0 /www/server/elasticsearch
    
    echo -e "${YELLOW}下载Logstash...${NC}"
    wget https://artifacts.elastic.co/downloads/logstash/logstash-7.10.0.tar.gz
    tar -xzf logstash-7.10.0.tar.gz
    mv logstash-7.10.0 /www/server/logstash
    
    echo -e "${YELLOW}下载Kibana...${NC}"
    wget https://artifacts.elastic.co/downloads/kibana/kibana-7.10.0-linux-x86_64.tar.gz
    tar -xzf kibana-7.10.0-linux-x86_64.tar.gz
    mv kibana-7.10.0-linux-x86_64 /www/server/kibana
    
    echo -e "${GREEN}✅ ELK Stack 安装完成！${NC}"
}

# 安装Ngrok
install_ngrok() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Ngrok内网穿透${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Ngrok" "ngrok" ""; then
        echo -e "${YELLOW}⚠️  Ngrok 已安装${NC}"
        read -p "是否要卸载现有Ngrok？(y/n，默认n): " uninstall_ngrok
        if [[ $uninstall_ngrok =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}正在彻底卸载Ngrok...${NC}"
            # 停止所有ngrok进程
            pkill -f ngrok 2>/dev/null
            
            # 删除所有可能的ngrok文件
            rm -f /usr/local/bin/ngrok
            rm -f /usr/bin/ngrok
            rm -f /bin/ngrok
            rm -rf ~/.ngrok2
            rm -rf ~/.ngrok
            
            # 清理可能的残留文件
            find /usr/local -name "*ngrok*" -delete 2>/dev/null
            find /usr/bin -name "*ngrok*" -delete 2>/dev/null
            
            echo -e "${GREEN}✅ Ngrok彻底卸载完成${NC}"
            
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
        else
            echo -e "${YELLOW}跳过Ngrok安装${NC}"
            return
        fi
    fi
    
    echo -e "${YELLOW}下载Ngrok稳定版本...${NC}"
    cd $INSTALL_DIR
    
    # 使用指定的下载源
    echo -e "${YELLOW}从指定源下载Ngrok...${NC}"
    if wget --timeout=60 --tries=3 https://xy-1306221339.file.myqcloud.com/install/linux/ngrok-v3-stable-linux-amd64.tgz 2>/dev/null; then
        echo -e "${GREEN}✅ 下载成功${NC}"
    else
        echo -e "${RED}❌ 下载失败${NC}"
        return 1
    fi
    
    # 解压并安装Ngrok
    echo -e "${YELLOW}解压并安装Ngrok...${NC}"
    tar -xzf ngrok-v3-stable-linux-amd64.tgz
    mv ngrok /usr/local/bin/
    chmod +x /usr/local/bin/ngrok
    
    # 清理下载文件
    rm -f ngrok-v3-stable-linux-amd64.tgz
    
    # 验证安装的版本
    echo -e "${YELLOW}验证Ngrok版本...${NC}"
    if command -v ngrok >/dev/null 2>&1; then
        NGROK_INSTALLED_VERSION=$(ngrok version 2>/dev/null | head -1 | grep -o 'v[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "未知版本")
        echo -e "${GREEN}✅ 安装成功，版本: ${CYAN}$NGROK_INSTALLED_VERSION${NC}"
        
        # 检查版本是否满足要求
        if [[ "$NGROK_INSTALLED_VERSION" =~ v([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
            MAJOR_VERSION=${BASH_REMATCH[1]}
            MINOR_VERSION=${BASH_REMATCH[2]}
            
            if [ "$MAJOR_VERSION" -ge 3 ] && [ "$MINOR_VERSION" -ge 7 ]; then
                echo -e "${GREEN}✅ 版本满足要求 (>= 3.7.0)${NC}"
            else
                echo -e "${RED}❌ 版本过低，尝试更新...${NC}"
                # 尝试自动更新
                ngrok update 2>/dev/null || echo -e "${YELLOW}自动更新失败，请手动更新${NC}"
            fi
        fi
    else
        echo -e "${RED}❌ Ngrok安装失败${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}创建Ngrok配置目录...${NC}"
    mkdir -p ~/.ngrok2
    
    # 交互式配置authtoken
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔑 Ngrok认证配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}请按以下步骤获取authtoken：${NC}"
    echo -e "  1. 注册账户: ${CYAN}https://ngrok.com${NC}"
    echo -e "  2. 根据自己的系统，下载客户端: ${CYAN}https://ngrok.com/download${NC}"
    echo -e "  3. 获取authToken: ${CYAN}https://dashboard.ngrok.com/auth${NC}"
    echo -e "  4. 在客户端输入: ${CYAN}ngrok authtoken 自己的token${NC}"
    echo
    echo -e "${YELLOW}注意：${NC}"
    echo -e "  • 本脚本会自动下载并安装Linux版本的Ngrok客户端"
    echo -e "  • 您只需要提供authtoken即可完成配置"
    echo -e "  • 如果您在其他系统上使用，请访问上述链接下载对应版本"
    echo
    read -p "请输入您的authtoken: " authtoken
    
    # 交互式配置端口
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🌐 端口配置${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}端口说明：${NC}"
    echo -e "  ${CYAN}HTTP端口${NC}: 用于Web服务穿透 (如: 80, 8080, 3000)"
    echo -e "  ${CYAN}注意${NC}: 免费账户仅支持HTTP隧道，TCP隧道需要付费账户"
    echo
    
    read -p "请输入HTTP端口 (默认80): " http_port
    http_port=${http_port:-80}
    
    # 自动写入配置文件
    echo -e "${YELLOW}创建Ngrok配置文件...${NC}"
    cat > ~/.ngrok2/ngrok.yml << EOF
authtoken: $authtoken
tunnels:
  web:
    proto: http
    addr: $http_port
EOF
    
    # 配置authtoken
    echo -e "${YELLOW}配置authtoken...${NC}"
    ngrok authtoken $authtoken
    
    echo -e "${YELLOW}配置开机自启动...${NC}"
    echo 'nohup /usr/local/bin/ngrok start --all &' >> /etc/rc.d/rc.local
    chmod +x /etc/rc.d/rc.local
    
    echo -e "${YELLOW}验证Ngrok安装...${NC}"
    ngrok version
    
    echo -e "${GREEN}✅ Ngrok 安装完成！${NC}"
    
    # 显示Ngrok管理面板
    show_ngrok_management_panel

}

# 安装Node.js
install_nodejs() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🔧 安装Node.js${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检测是否已安装
    if check_component_installed "Node.js" "node" "/usr/local/node"; then
        echo -e "${YELLOW}⚠️  Node.js 已安装${NC}"
        read -p "是否要卸载现有Node.js？(y/n，默认n): " uninstall_nodejs
        if [[ $uninstall_nodejs =~ ^[Yy]$ ]]; then
            uninstall_component "Node.js" "rm -rf /usr/local/node"
            # 检查是否要重新安装
            if [ $? -eq 1 ]; then
                return
            fi
            # 清理环境变量
            sed -i '/NODE_HOME/d' /etc/profile
            sed -i '/export PATH.*node/d' /etc/profile
        else
            echo -e "${YELLOW}跳过Node.js安装${NC}"
            return
        fi
    fi
    
    # 检测系统版本和GLIBC版本
    echo -e "${YELLOW}检测系统兼容性...${NC}"
    GLIBC_VERSION=$(ldd --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -n1)
    SYSTEM_VERSION=$(cat /etc/redhat-release 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME)
    
    echo -e "${CYAN}系统信息: $SYSTEM_VERSION${NC}"
    echo -e "${CYAN}GLIBC版本: $GLIBC_VERSION${NC}"
    
    # 根据系统版本选择合适的Node.js版本
    if [[ "$GLIBC_VERSION" < "2.27" ]]; then
        NODE_VERSION="16.20.2"
        NODE_URL="https://mirrors.aliyun.com/nodejs-release/v16.20.2/node-v16.20.2-linux-x64.tar.xz"
        echo -e "${YELLOW}检测到较旧的系统，将安装Node.js v16.20.2 LTS (兼容性更好)${NC}"
    else
        NODE_VERSION="22.11.0"
        NODE_URL="https://mirrors.aliyun.com/nodejs-release/v22.11.0/node-v22.11.0-linux-x64.tar.xz"
        echo -e "${YELLOW}系统兼容性良好，将安装Node.js v22.11.0${NC}"
    fi
    
    mkdir -p $INSTALL_DIR
    cd $INSTALL_DIR
    
    echo -e "${YELLOW}正在下载Node.js v$NODE_VERSION...${NC}"
    wget $NODE_URL
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Node.js下载失败${NC}"
        echo -e "${YELLOW}尝试使用官方源下载...${NC}"
        NODE_URL_OFFICIAL="https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz"
        wget $NODE_URL_OFFICIAL
        if [ $? -ne 0 ]; then
            echo -e "${RED}❌ Node.js下载失败，请检查网络连接${NC}"
            return 1
        fi
    fi
    
    echo -e "${YELLOW}正在解压Node.js...${NC}"
    tar -xJf node-v$NODE_VERSION-linux-x64.tar.xz
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Node.js解压失败${NC}"
        return 1
    fi
    
    mv node-v$NODE_VERSION-linux-x64 /usr/local/node
    
    echo -e "${YELLOW}配置Node.js环境变量...${NC}"
    echo 'export NODE_HOME=/usr/local/node' >> /etc/profile
    echo 'export PATH=$NODE_HOME/bin:$PATH' >> /etc/profile
    source /etc/profile
    
    echo -e "${YELLOW}验证Node.js安装...${NC}"
    if /usr/local/node/bin/node --version >/dev/null 2>&1; then
        echo -e "${GREEN}✅ Node.js版本: $(/usr/local/node/bin/node --version)${NC}"
        echo -e "${GREEN}✅ npm版本: $(/usr/local/node/bin/npm --version)${NC}"
        
        echo -e "${YELLOW}配置npm镜像源...${NC}"
        /usr/local/node/bin/npm config set registry https://registry.npmmirror.com
        
        echo -e "${GREEN}✅ Node.js v$NODE_VERSION 安装完成！${NC}"
        echo -e "${CYAN}💡 使用说明：${NC}"
        echo -e "  • 重新加载环境变量: source /etc/profile"
        echo -e "  • 检查版本: node --version"
        echo -e "  • 全局安装包: npm install -g <package>"
        echo -e "  • 查看npm配置: npm config list"
    else
        echo -e "${RED}❌ Node.js安装验证失败${NC}"
        echo -e "${YELLOW}可能的解决方案：${NC}"
        echo -e "  1. 检查系统是否支持该Node.js版本"
        echo -e "  2. 尝试安装更旧的Node.js版本"
        echo -e "  3. 更新系统库: yum update glibc"
        echo -e "  4. 使用包管理器安装: yum install nodejs npm"
        return 1
    fi
}

# 开始安装
start_installation() {
    echo -e "\n${CYAN}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}                    🚀 开始安装组件${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 创建必要的目录
    mkdir -p $INSTALL_DIR
    mkdir -p $WWW_DIR
    
    # 安装选中的组件
    if [ $Jdk == "1" ]; then install_jdk; fi
    if [ $Tomcat == "1" ]; then install_tomcat; fi
    if [ $Maven == "1" ]; then install_maven; fi
    if [ $Nginx == "1" ]; then 
        install_nginx
        # 检查Nginx安装函数的返回值
        if [ $? -eq 2 ]; then
            # 如果返回2，说明用户选择返回安装页，继续安装下一个组件
            echo -e "\n${CYAN}"
            echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            echo -e "${WHITE}                    🔄 继续安装流程${NC}"
            echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            echo
            echo -e "${WHITE}📋 安装进度：${NC}"
            echo -e "${GREEN}✅ Nginx 安装完成${NC}"
            echo -e "${YELLOW}🔄 继续安装下一个组件...${NC}"
            echo
            echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        else
            # Nginx安装完成后会自动跳转到管理面板，这里不需要继续执行
            return
        fi
    fi
    if [ $MySQL == "1" ]; then install_mysql; fi
    if [ $Redis == "1" ]; then install_redis; fi
    if [ $SVN == "1" ]; then install_svn; fi
    if [ $FTP == "1" ]; then install_ftp; fi
    if [ $ZooKeeper == "1" ]; then install_zookeeper; fi
    if [ $RabbitMQ == "1" ]; then install_rabbitmq; fi
    if [ $Kafka == "1" ]; then install_kafka; fi
    if [ $ELK == "1" ]; then install_elk; fi
    if [ $Ngrok == "1" ]; then install_ngrok; fi
    if [ $Nodejs == "1" ]; then install_nodejs; fi
    
    echo -e "\n${CYAN}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}                    🎉 安装完成总结${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo
    echo -e "${WHITE}📊 安装状态：${NC}"
    echo -e "${GREEN}✅ 所选的组件已经安装完成！${NC}"
    echo
    echo -e "${WHITE}🔧 环境配置：${NC}"
    echo -e "${YELLOW}⚠️  请执行 'source /etc/profile' 使环境变量生效${NC}"
    echo
    echo -e "${WHITE}📁 安装路径信息：${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}JDK:${NC} ${GREEN}/usr/java/jdk1.8.0_131${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Tomcat:${NC} ${GREEN}/www/server/tomcat${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Maven:${NC} ${GREEN}/www/server/maven${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Redis:${NC} ${GREEN}/www/server/redis${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}ZooKeeper:${NC} ${GREEN}/www/server/zookeeper${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Kafka:${NC} ${GREEN}/www/server/kafka${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Elasticsearch:${NC} ${GREEN}/www/server/elasticsearch${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Logstash:${NC} ${GREEN}/www/server/logstash${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Kibana:${NC} ${GREEN}/www/server/kibana${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Node.js:${NC} ${GREEN}/www/server/node${NC}"
    echo
    echo -e "${WHITE}💡 使用提示：${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}执行 'source /etc/profile' 使环境变量生效${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}各组件配置文件位于对应安装目录的 conf 文件夹${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}日志文件通常位于 /var/log/ 目录下${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}服务管理使用 systemctl start/stop/restart 命令${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Tomcat服务: systemctl start/stop/restart tomcat${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}Tomcat访问: http://$(curl -s ipinfo.io/ip):8080${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}MySQL服务: systemctl start/stop/restart mysqld${NC}"
    echo -e "${CYAN}•${NC} ${WHITE}MySQL连接: mysql -u root -P [端口号]${NC}"
    echo
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🎉 恭喜！您的开发环境已成功部署完成！${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# 主菜单循环
main_menu() {
    # 显示初始菜单
    show_install_menu
    read -p "请选择组件 [0-14]: " choice
    handle_component_selection "$choice"
}

# 处理组件选择
handle_component_selection() {
    local choice="$1"
    case $choice in
        1) 
            if [ $Jdk == "1" ]; then
                echo -e "${YELLOW}⚠️  JDK 1.8 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Jdk=1
                echo -e "${GREEN}✅ 已选择安装JDK 1.8${NC}"
                show_continue_prompt
            fi
            ;;
        2) 
            if [ $Tomcat == "1" ]; then
                echo -e "${YELLOW}⚠️  Tomcat 9.x 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Tomcat=1
                echo -e "${GREEN}✅ 已选择安装Tomcat 9.x${NC}"
                show_continue_prompt
            fi
            ;;
        3) 
            if [ $Maven == "1" ]; then
                echo -e "${YELLOW}⚠️  Maven 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Maven=1
                echo -e "${GREEN}✅ 已选择安装Maven${NC}"
                show_continue_prompt
            fi
            ;;
        4) 
            if [ $Nginx == "1" ]; then
                echo -e "${YELLOW}⚠️  Nginx 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Nginx=1
                echo -e "${GREEN}✅ 已选择安装Nginx${NC}"
                show_continue_prompt
            fi
            ;;
        5) 
            if [ $MySQL == "1" ]; then
                echo -e "${YELLOW}⚠️  MySQL 5.7 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                MySQL=1
                echo -e "${GREEN}✅ 已选择安装MySQL 5.7${NC}"
                show_continue_prompt
            fi
            ;;
        6) 
            if [ $ELK == "1" ]; then
                echo -e "${YELLOW}⚠️  ELK Stack 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                ELK=1
                echo -e "${GREEN}✅ 已选择安装ELK Stack${NC}"
                show_continue_prompt
            fi
            ;;
        7) 
            if [ $Redis == "1" ]; then
                echo -e "${YELLOW}⚠️  Redis 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Redis=1
                echo -e "${GREEN}✅ 已选择安装Redis${NC}"
                show_continue_prompt
            fi
            ;;
        8) 
            if [ $SVN == "1" ]; then
                echo -e "${YELLOW}⚠️  SVN 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                SVN=1
                echo -e "${GREEN}✅ 已选择安装SVN${NC}"
                show_continue_prompt
            fi
            ;;
        9) 
            if [ $FTP == "1" ]; then
                echo -e "${YELLOW}⚠️  FTP 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                FTP=1
                echo -e "${GREEN}✅ 已选择安装FTP${NC}"
                show_continue_prompt
            fi
            ;;
        10) 
            if [ $ZooKeeper == "1" ]; then
                echo -e "${YELLOW}⚠️  ZooKeeper 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                ZooKeeper=1
                echo -e "${GREEN}✅ 已选择安装ZooKeeper${NC}"
                show_continue_prompt
            fi
            ;;
        11) 
            if [ $RabbitMQ == "1" ]; then
                echo -e "${YELLOW}⚠️  RabbitMQ 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                RabbitMQ=1
                echo -e "${GREEN}✅ 已选择安装RabbitMQ${NC}"
                show_continue_prompt
            fi
            ;;
        12) 
            if [ $Kafka == "1" ]; then
                echo -e "${YELLOW}⚠️  Kafka 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Kafka=1
                echo -e "${GREEN}✅ 已选择安装Kafka${NC}"
                show_continue_prompt
            fi
            ;;
        13) 
            if [ $Ngrok == "1" ]; then
                echo -e "${YELLOW}⚠️  Ngrok 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Ngrok=1
                echo -e "${GREEN}✅ 已选择安装Ngrok${NC}"
                show_continue_prompt
            fi
            ;;
        14) 
            if [ $Nodejs == "1" ]; then
                echo -e "${YELLOW}⚠️  Node.js 已经选择过了${NC}"
                echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
                echo
                show_continue_prompt
            else
                Nodejs=1
                echo -e "${GREEN}✅ 已选择安装Node.js${NC}"
                show_continue_prompt
            fi
            ;;
        0) 
            echo -e "${YELLOW}重新选择组件...${NC}"
            # 重置所有选择
            Jdk=0; Tomcat=0; Maven=0; Nginx=0; MySQL=0; Redis=0; SVN=0; FTP=0; ZooKeeper=0; RabbitMQ=0; Kafka=0; ELK=0; Ngrok=0; Nodejs=0
            echo -e "${GREEN}✅ 已重置所有选择${NC}"
            echo
            main_menu
            ;;
        *) 
            echo -e "${RED}❌ 无效选择，请输入 0-14${NC}"
            echo -e "${YELLOW}💡 输入 0 重新选择，Ctrl+C 关闭脚本${NC}"
            echo
            # 显示功能面板和已选择列表
            show_install_menu
            echo
            show_selected_components
            read -p "请选择组件 [0-14]: " action
            case $action in
                start|START|Start) 
                    show_installation_confirmation
                    ;;
                0) 
                    echo -e "${YELLOW}重新选择组件...${NC}"
                    # 重置所有选择
                    Jdk=0; Tomcat=0; Maven=0; MySQL=0; Nginx=0; Redis=0; SVN=0; FTP=0; ZooKeeper=0; RabbitMQ=0; Kafka=0; ELK=0; Ngrok=0
                    echo -e "${GREEN}✅ 已重置所有选择${NC}"
                    echo
                    main_menu
                    ;;
                *) 
                    # 递归处理，避免无限循环
                    handle_component_selection "$action"
                    ;;
            esac
            ;;
    esac
}

# 显示继续添加提示
show_continue_prompt() {
    local selected_count=0
    
    # 统计已选择的组件
    if [ $Jdk == "1" ]; then ((selected_count++)); fi
    if [ $Tomcat == "1" ]; then ((selected_count++)); fi
    if [ $Maven == "1" ]; then ((selected_count++)); fi
    if [ $Nginx == "1" ]; then ((selected_count++)); fi
    if [ $MySQL == "1" ]; then ((selected_count++)); fi
    if [ $Redis == "1" ]; then ((selected_count++)); fi
    if [ $SVN == "1" ]; then ((selected_count++)); fi
    if [ $FTP == "1" ]; then ((selected_count++)); fi
    if [ $ZooKeeper == "1" ]; then ((selected_count++)); fi
    if [ $RabbitMQ == "1" ]; then ((selected_count++)); fi
    if [ $Kafka == "1" ]; then ((selected_count++)); fi
    if [ $ELK == "1" ]; then ((selected_count++)); fi
    if [ $Ngrok == "1" ]; then ((selected_count++)); fi
    if [ $Nodejs == "1" ]; then ((selected_count++)); fi
    
    if [ $selected_count -gt 0 ]; then
        # 显示功能面板
        show_install_menu
        # 显示已选择组件列表
        show_selected_components
        echo
        
        echo -e "${YELLOW}💡 回车继续添加，输入1开始安装${NC}"
        read -p "请选择操作: " action
        case $action in
            1) 
                show_installation_confirmation
                ;;
            "") 
                # 回车继续添加
                read -p "请选择组件 [0-13]: " component_choice
                case $component_choice in
                    0) 
                        echo -e "${YELLOW}重新选择组件...${NC}"
                        # 重置所有选择
                        Jdk=0; Tomcat=0; Maven=0; Nginx=0; MySQL=0; Redis=0; SVN=0; FTP=0; ZooKeeper=0; RabbitMQ=0; Kafka=0; ELK=0; Ngrok=0; Nodejs=0
                        echo -e "${GREEN}✅ 已重置所有选择${NC}"
                        echo
                        main_menu
                        ;;
                    *) 
                        # 直接处理组件选择
                        handle_component_selection "$component_choice"
                        ;;
                esac
                ;;
            *) 
                # 其他输入当作组件选择处理
                handle_component_selection "$action"
                ;;
        esac
    else
        echo -e "${YELLOW}💡 请继续选择要安装的组件${NC}"
        echo
        main_menu
    fi
}



# 显示安装确认界面
show_installation_confirmation() {
    local selected_count=0
    local selected_items=()
    
    # 统计已选择的组件
    if [ $Jdk == "1" ]; then selected_items+=("JDK 1.8"); ((selected_count++)); fi
    if [ $Tomcat == "1" ]; then selected_items+=("Tomcat 9.x"); ((selected_count++)); fi
    if [ $Maven == "1" ]; then selected_items+=("Maven"); ((selected_count++)); fi
    if [ $Nginx == "1" ]; then selected_items+=("Nginx"); ((selected_count++)); fi
    if [ $MySQL == "1" ]; then selected_items+=("MySQL 5.7"); ((selected_count++)); fi
    if [ $Redis == "1" ]; then selected_items+=("Redis"); ((selected_count++)); fi
    if [ $SVN == "1" ]; then selected_items+=("SVN"); ((selected_count++)); fi
    if [ $FTP == "1" ]; then selected_items+=("FTP"); ((selected_count++)); fi
    if [ $ZooKeeper == "1" ]; then selected_items+=("ZooKeeper"); ((selected_count++)); fi
    if [ $RabbitMQ == "1" ]; then selected_items+=("RabbitMQ"); ((selected_count++)); fi
    if [ $Kafka == "1" ]; then selected_items+=("Kafka"); ((selected_count++)); fi
    if [ $ELK == "1" ]; then selected_items+=("ELK Stack"); ((selected_count++)); fi
    if [ $Ngrok == "1" ]; then selected_items+=("Ngrok"); ((selected_count++)); fi
    
    clear
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}安装确认界面${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}即将安装以下 ${GREEN}$selected_count${NC} 个组件：${NC}"
    echo
    
    # 显示要安装的组件
    for item in "${selected_items[@]}"; do
        echo -e "${CYAN}✅ ${NC} ${WHITE}$item${NC}"
    done
    echo
    echo -e "${YELLOW}安装路径：${CYAN}/www/server${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    read -p "确认开始安装？(y/n，默认y): " confirm
    confirm=${confirm:-y}
    
    if [[ $confirm =~ ^[Yy]$ ]]; then
        start_installation
        return
    else
        echo -e "${YELLOW}已取消安装，返回选择菜单${NC}"
        echo -e "\n${YELLOW}按回车键继续...${NC}"
        read
        return
    fi
}

# 创建欢迎页面
create_welcome_page() {
    local domain="$1"
    local site_root="$2"
    local current_time=$(date '+%Y-%m-%d %H:%M:%S')
    local server_ip=$(hostname -I | awk '{print $1}')
    
    echo -e "${YELLOW}正在创建欢迎页面...${NC}"
    
    # 检查index.html是否已存在
    if [ -f "$site_root/index.html" ]; then
        echo -e "${YELLOW}⚠️  欢迎页面已存在: $site_root/index.html${NC}"
        read -p "是否要覆盖现有欢迎页面？(y/n，默认n): " overwrite_welcome
        if [[ ! $overwrite_welcome =~ ^[Yy]$ ]]; then
            echo -e "${YELLOW}跳过创建欢迎页面${NC}"
            return
        fi
    fi
    
    # 创建欢迎页面HTML文件
    cat > "$site_root/index.html" << 'HTML_EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>站点部署成功 - 欢迎访问</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            max-width: 1100px;
            width: 85%;
            text-align: center;
            position: relative;
            overflow: hidden;
            margin: 30px auto;
        }
        
        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2, #f093fb);
        }
        
        .success-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #4CAF50, #45a049);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 30px;
            animation: pulse 2s infinite;
        }
        
        .success-icon::after {
            content: '✓';
            color: white;
            font-size: 40px;
            font-weight: bold;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        h1 {
            color: #2c3e50;
            font-size: 2.5em;
            margin-bottom: 20px;
            font-weight: 300;
        }
        
        .subtitle {
            color: #7f8c8d;
            font-size: 1.2em;
            margin-bottom: 40px;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        
        .info-card {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            padding: 25px;
            border-radius: 15px;
            border-left: 4px solid #667eea;
            text-align: left;
            transition: transform 0.3s ease;
        }
        
        .info-card:hover {
            transform: translateY(-5px);
        }
        
        .info-card h3 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 1.1em;
        }
        
        .info-card p {
            color: #7f8c8d;
            font-family: 'Courier New', monospace;
            background: #fff;
            padding: 8px 12px;
            border-radius: 5px;
            border: 1px solid #e9ecef;
            word-break: break-all;
        }
        
        .status-badge {
            display: inline-block;
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .upload-info {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .upload-info h3 {
            color: #856404;
            margin-bottom: 15px;
        }
        
        .upload-info ul {
            list-style: none;
            padding: 0;
        }
        
        .upload-info li {
            color: #856404;
            margin: 8px 0;
            padding-left: 20px;
            position: relative;
        }
        
        .upload-info li::before {
            content: '📁';
            position: absolute;
            left: 0;
        }
        
        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
            color: #7f8c8d;
            font-size: 0.9em;
        }
        
        .footer a {
            color: #667eea;
            text-decoration: none;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 20px;
            }
            
            h1 {
                font-size: 2em;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="success-icon"></div>
        
        <h1>🎉 站点部署成功</h1>
        <p class="subtitle">恭喜！您的网站已经成功部署并可以正常访问</p>
        
        <div class="status-badge">✅ 运行状态：正常</div>
        
        <div class="info-grid">
            <div class="info-card">
                <h3>🌐 站点信息</h3>
                <p>站点域名名称：DOMAIN_PLACEHOLDER</p>
                <p>服务器外网IP：$(curl -s ipinfo.io/ip)</p>
                <p>服务器内网IP：SERVER_IP_PLACEHOLDER</p>
            </div>
            
            <div class="info-card">
                <h3>📂 站点配置</h3>
                <p>网站目录：SITE_ROOT_PLACEHOLDER</p>
                <p>配置文件：NGINX_CONFIG_PLACEHOLDER</p>
                <p>部署时间：DEPLOY_TIME_PLACEHOLDER</p>
            </div>
        </div>
        
        <div class="upload-info">
            <h3>📤 文件上传说明</h3>
            <ul>
                <li>网站根目录：SITE_ROOT_PLACEHOLDER</li>
                <li>上传方式：FTP/SFTP/SCP</li>
                <li>默认首页：index.html</li>
                <li>支持格式：HTML、CSS、JS、图片等</li>
            </ul>
        </div>
        
        <div class="footer">
            <p>🚀 由 <a href="#" target="_blank">一键环境部署脚本</a> 自动构建生成</p>
            <p>💡 如需修改此页面，请替换 index.html 文件</p>
        </div>
    </div>
    
    <script>
        // 动态更新信息
        document.addEventListener('DOMContentLoaded', function() {
            // 获取当前域名
            const currentDomain = window.location.hostname;
            document.querySelectorAll('.info-card p').forEach(function(p) {
                p.textContent = p.textContent.replace('DOMAIN_PLACEHOLDER', currentDomain);
            });
            
            // 添加一些交互效果
            const cards = document.querySelectorAll('.info-card');
            cards.forEach(function(card, index) {
                card.style.animationDelay = (index * 0.1) + 's';
                card.style.animation = 'fadeInUp 0.6s ease forwards';
            });
        });
        
        // 添加淡入动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeInUp {
                from {
                    opacity: 0;
                    transform: translateY(30px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
HTML_EOF

    # 替换占位符
    sed -i "s/DOMAIN_PLACEHOLDER/$domain/g" "$site_root/index.html"
    sed -i "s/SERVER_IP_PLACEHOLDER/$server_ip/g" "$site_root/index.html"
    sed -i "s/DEPLOY_TIME_PLACEHOLDER/$current_time/g" "$site_root/index.html"
    sed -i "s|SITE_ROOT_PLACEHOLDER|$site_root|g" "$site_root/index.html"
    
    # 确定Nginx配置文件路径
    local nginx_config_path
    if [ -f "/etc/nginx/conf.d/$domain.conf" ]; then
        nginx_config_path="/etc/nginx/conf.d/$domain.conf"
    elif [ -f "/etc/nginx/sites-available/$domain.conf" ]; then
        nginx_config_path="/etc/nginx/sites-available/$domain.conf"
    else
        nginx_config_path="未找到配置文件"
    fi
    sed -i "s|NGINX_CONFIG_PLACEHOLDER|$nginx_config_path|g" "$site_root/index.html"
    
    # 设置文件权限
    chmod 644 "$site_root/index.html"
    
    echo -e "${GREEN}✅ 欢迎页面创建完成！${NC}"
    echo -e "${CYAN}访问地址: http://$domain${NC}"
    echo -e "${CYAN}页面路径: $site_root/index.html${NC}"
}

# Ngrok管理面板
show_ngrok_management_panel() {
    while true; do
        echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${WHITE}🌐 Ngrok 管理面板${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        
        # 显示服务状态
        if pgrep -x "ngrok" > /dev/null; then
            echo -e "${GREEN}📊 服务状态：✅ 运行中${NC}"
        else
            echo -e "${RED}📊 服务状态：❌ 未运行${NC}"
        fi
        
        echo -e "${YELLOW}🔧 管理功能：${NC}"
        echo -e "  1. 启动Ngrok服务"
        echo -e "  2. 停止Ngrok服务"
        echo -e "  3. 查看隧道状态"
        echo -e "  4. 查看服务日志"
        echo -e "  5. 客户端下载指导"
        echo -e "  6. 使用教程"
        echo -e "  7. 固定域名申请"
        echo -e "  8. 配置文件管理"
        echo -e "  9. 服务监控"
        echo -e "  0. 返回主菜单"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        
        read -p "请选择 [0-9]: " choice
        
        case $choice in
            1)
                start_ngrok_service
                ;;
            2)
                stop_ngrok_service
                ;;
            3)
                show_tunnel_status
                ;;
            4)
                show_ngrok_logs
                ;;
            5)
                show_client_download
                ;;
            6)
                show_usage_tutorial
                ;;
            7)
                show_fixed_domain_info
                ;;
            8)
                manage_ngrok_config
                ;;
            9)
                show_ngrok_monitor
                ;;
            0)
                echo -e "${YELLOW}返回主菜单...${NC}"
                return
                ;;
            *)
                echo -e "${RED}❌ 无效选择，请重新输入${NC}"
                ;;
        esac
        
        echo -e "\n${YELLOW}按回车键继续...${NC}"
        read
    done
}

# 启动Ngrok服务
start_ngrok_service() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🚀 启动Ngrok服务${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if pgrep -x "ngrok" > /dev/null; then
        echo -e "${YELLOW}⚠️  Ngrok服务已在运行中${NC}"
        return
    fi
    
    echo -e "${YELLOW}正在启动Ngrok服务...${NC}"
    nohup ngrok start --all --log=stdout > ~/.ngrok2/ngrok.log 2>&1 &
    
    sleep 3
    
    if pgrep -x "ngrok" > /dev/null; then
        echo -e "${GREEN}✅ Ngrok服务启动成功！${NC}"
        echo -e "${CYAN}管理界面: http://$(curl -s ipinfo.io/ip):4040${NC}"
        echo -e "${CYAN}隧道状态: http://$(curl -s ipinfo.io/ip):4040/api/tunnels${NC}"
    else
        echo -e "${RED}❌ Ngrok服务启动失败${NC}"
        echo -e "${YELLOW}请检查日志: tail -f ~/.ngrok2/ngrok.log${NC}"
    fi
}

# 停止Ngrok服务
stop_ngrok_service() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🛑 停止Ngrok服务${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if ! pgrep -x "ngrok" > /dev/null; then
        echo -e "${YELLOW}⚠️  Ngrok服务未运行${NC}"
        return
    fi
    
    echo -e "${YELLOW}正在停止Ngrok服务...${NC}"
    pkill -f ngrok
    
    sleep 2
    
    if ! pgrep -x "ngrok" > /dev/null; then
        echo -e "${GREEN}✅ Ngrok服务已停止${NC}"
    else
        echo -e "${RED}❌ 停止服务失败，请手动检查${NC}"
    fi
}

# 查看隧道状态
show_tunnel_status() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📊 隧道状态${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if ! pgrep -x "ngrok" > /dev/null; then
        echo -e "${RED}❌ Ngrok服务未运行${NC}"
        return
    fi
    
    echo -e "${YELLOW}正在获取隧道状态...${NC}"
    curl -s http://localhost:4040/api/tunnels 2>/dev/null | python3 -m json.tool 2>/dev/null || echo -e "${RED}无法获取隧道状态${NC}"
}

# 查看Ngrok日志
show_ngrok_logs() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📋 Ngrok日志${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if [ -f ~/.ngrok2/ngrok.log ]; then
        echo -e "${YELLOW}最后20行日志：${NC}"
        tail -20 ~/.ngrok2/ngrok.log
    else
        echo -e "${RED}❌ 日志文件不存在${NC}"
    fi
}

# 客户端下载指导
show_client_download() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}💻 客户端下载指导${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}📥 下载地址：${NC}"
    echo -e "  Windows: ${CYAN}https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-windows-amd64.zip${NC}"
    echo -e "  macOS: ${CYAN}https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-darwin-amd64.zip${NC}"
    echo -e "  Linux: ${CYAN}https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.zip${NC}"
    echo -e "  官方下载: ${CYAN}https://ngrok.com/download${NC}"
    
    echo -e "\n${YELLOW}🔧 安装步骤：${NC}"
    echo -e "  1. 下载对应系统的压缩包"
    echo -e "  2. 解压到任意目录"
    echo -e "  3. 将ngrok.exe(Windows)或ngrok(Linux/macOS)添加到PATH环境变量"
    echo -e "  4. 打开命令行验证: ngrok version"
}

# 使用教程
show_usage_tutorial() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📚 使用教程${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}🔑 第一步：配置authtoken${NC}"
    echo -e "  ${CYAN}ngrok config add-authtoken 你的authtoken${NC}"
    echo -e "  示例: ngrok config add-authtoken 2abc123def456ghi789jkl"
    
    echo -e "\n${YELLOW}🌐 第二步：启动HTTP隧道${NC}"
    echo -e "  ${CYAN}ngrok http 需要映射的地址${NC}"
    echo -e "  示例: ngrok http http://localhost:8888"
    echo -e "  示例: ngrok http 8080"
    
    echo -e "\n${YELLOW}🔧 高级用法：${NC}"
    echo -e "  • 指定端口: ${CYAN}ngrok http 3000${NC}"
    echo -e "  • 指定域名: ${CYAN}ngrok http --domain=your-domain.ngrok.io 8080${NC}"
    echo -e "  • 后台运行: ${CYAN}nohup ngrok http 8080 > ngrok.log 2>&1 &${NC}"
    echo -e "  • 查看状态: ${CYAN}curl http://localhost:4040/api/tunnels${NC}"
    
    echo -e "\n${YELLOW}📱 移动端使用：${NC}"
    echo -e "  • 下载ngrok移动端APP"
    echo -e "  • 扫描二维码连接"
    echo -e "  • 或手动输入authtoken"
}

# 固定域名申请
show_fixed_domain_info() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}🌍 固定域名申请${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}🎯 申请固定域名的好处：${NC}"
    echo -e "  • 域名不会随机变化"
    echo -e "  • 便于分享和记忆"
    echo -e "  • 支持自定义子域名"
    echo -e "  • 提高访问稳定性"
    
    echo -e "\n${YELLOW}📝 申请步骤：${NC}"
    echo -e "  1. 访问: ${CYAN}https://dashboard.ngrok.com/domains${NC}"
    echo -e "  2. 登录您的ngrok账户"
    echo -e "  3. 点击'New Domain'"
    echo -e "  4. 输入您想要的域名前缀"
    echo -e "  5. 选择地区（建议选择离您最近的）"
    echo -e "  6. 确认申请"
    
    echo -e "\n${YELLOW}🔧 使用固定域名：${NC}"
    echo -e "  ${CYAN}ngrok http --domain=your-domain.ngrok.io 8080${NC}"
    echo -e "  示例: ngrok http --domain=myapp.ngrok.io 3000"
    
    echo -e "\n${YELLOW}⚠️  注意事项：${NC}"
    echo -e "  • 免费账户限制域名数量"
    echo -e "  • 付费账户可申请更多域名"
    echo -e "  • 域名申请后需要等待审核"
}

# 配置文件管理
manage_ngrok_config() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}⚙️  配置文件管理${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}📁 配置文件位置：${NC}"
    echo -e "  Linux/macOS: ${CYAN}~/.ngrok2/ngrok.yml${NC}"
    echo -e "  Windows: ${CYAN}%USERPROFILE%/.ngrok2/ngrok.yml${NC}"
    
    echo -e "\n${YELLOW}📋 当前配置：${NC}"
    if [ -f ~/.ngrok2/ngrok.yml ]; then
        cat ~/.ngrok2/ngrok.yml
    else
        echo -e "${RED}❌ 配置文件不存在${NC}"
    fi
    
    echo -e "\n${YELLOW}🔧 配置选项：${NC}"
    echo -e "  1. 查看配置"
    echo -e "  2. 编辑配置"
    echo -e "  3. 备份配置"
    echo -e "  4. 重置配置"
    
    read -p "请选择 [1-4]: " config_choice
    
    case $config_choice in
        1)
            echo -e "${CYAN}配置文件内容：${NC}"
            cat ~/.ngrok2/ngrok.yml 2>/dev/null || echo -e "${RED}配置文件不存在${NC}"
            ;;
        2)
            echo -e "${YELLOW}使用编辑器打开配置文件...${NC}"
            ${EDITOR:-vi} ~/.ngrok2/ngrok.yml
            ;;
        3)
            cp ~/.ngrok2/ngrok.yml ~/.ngrok2/ngrok.yml.backup.$(date +%Y%m%d_%H%M%S)
            echo -e "${GREEN}✅ 配置已备份${NC}"
            ;;
        4)
            read -p "确定要重置配置吗？(y/n): " reset_confirm
            if [[ $reset_confirm =~ ^[Yy]$ ]]; then
                rm -f ~/.ngrok2/ngrok.yml
                echo -e "${GREEN}✅ 配置已重置${NC}"
            fi
            ;;
    esac
}

# 服务监控
show_ngrok_monitor() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${WHITE}📊 服务监控${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    echo -e "${YELLOW}🔍 进程状态：${NC}"
    if pgrep -x "ngrok" > /dev/null; then
        echo -e "${GREEN}✅ Ngrok进程正在运行${NC}"
        ps -ef | grep ngrok | grep -v grep
    else
        echo -e "${RED}❌ Ngrok进程未运行${NC}"
    fi
    
    echo -e "\n${YELLOW}🌐 端口监听：${NC}"
    netstat -tlnp | grep :4040 || echo -e "${RED}4040端口未监听${NC}"
    
    echo -e "\n${YELLOW}💾 资源使用：${NC}"
    if pgrep -x "ngrok" > /dev/null; then
        ngrok_pid=$(pgrep -x "ngrok")
        echo -e "  进程ID: ${CYAN}$ngrok_pid${NC}"
        echo -e "  内存使用: ${CYAN}$(ps -o rss= -p $ngrok_pid | awk '{print $1/1024 " MB"}')${NC}"
        echo -e "  CPU使用: ${CYAN}$(ps -o %cpu= -p $ngrok_pid)%${NC}"
    fi
    
    echo -e "\n${YELLOW}📈 实时监控：${NC}"
    echo -e "  管理界面: ${CYAN}http://localhost:4040${NC}"
    echo -e "  API状态: ${CYAN}http://localhost:4040/api/tunnels${NC}"
}

# 主程序
main() {
    show_welcome
    main_menu
}

# 运行主程序
main
